两个进程同时更新一个文件,如何同步这两个进程??

解决方案 »

  1.   

    两个进程要使用同一个资源,这明显是互斥操作,lz说同步不明白,如果控制访问顺序什么的可以试试信号量Mutex类
      

  2.   

    听着就迷糊,如果更新的内容有冲突,那没办法,自己加事物 顺序执行。
    如果更新的不冲突,还在同一文件(前提是能够同时操作这文件)。自己加个标志表示要更新的东西是独立的。
    互斥就是有你没我的意思,同一时间我们两个只有一个能操作这文件。数据库 可以加锁。文件在.net中操作好像本身就是互斥的。据我所知,和一个文件交互的流在同一时刻只能有一个。要不把要改的都写在这个流里,一起更新?
      

  3.   

    如果是unix可以用文件加锁的方法。The LockFile function locks a region in an open file. Locking a region prevents other processes from accessing the region. BOOL LockFile(    HANDLE hFile, // handle of file to lock 
        DWORD dwFileOffsetLow, // low-order word of lock region offset 
        DWORD dwFileOffsetHigh, // high-order word of lock region offset  
        DWORD nNumberOfBytesToLockLow, // low-order word of length to lock 
        DWORD nNumberOfBytesToLockHigh  // high-order word of length to lock 
       );
     ParametershFileIdentifies the file with a region to be locked. The file handle must have been created with GENERIC_READ or GENERIC_WRITE access to the file (or both). dwFileOffsetLowSpecifies the low-order word of the starting byte offset in the file where the lock should begin. dwFileOffsetHighSpecifies the high-order word of the starting byte offset in the file where the lock should begin. nNumberOfBytesToLockLowSpecifies the low-order word of the length of the byte range to be locked. nNumberOfBytesToLockHighSpecifies the high-order word of the length of the byte range to be locked.  Return ValuesIf the function succeeds, the return value is nonzero.
    If the function fails, the return value is zero. To get extended error information, call GetLastError. ResLocking a region of a file gives the locking process exclusive access to the specified region. File locks are not inherited by processes created by the locking process. 
    Locking a region of a file denies all other processes both read and write access to the specified region. Locking a region that goes beyond the current end-of-file position is not an error. 
    Locks may not overlap an existing locked region of the file. 
      

  4.   

    独占打开下一个更新会出错吧。这样做看看是否行了:首先保证访问这个文件只由一个实例(注意不是类)或静态方法来完成,其次在更新文件前先锁定一个对象(同样静态或唯一实例)。如:
    public class WriteFile
    {
        private static object obj = new object();
        public static void WriteLine(string str)
        {
            lock(obj)
            {
                //打开,写入,关闭文件代码
            }
        }
    }
    可以用singleton模式来保证单一实例。
      

  5.   

    用Mutex类试试,它可以同步进程