你的位置:首页 > ASP.net教程

[ASP.net教程]文件读写锁


避免文件被死锁,lock 确保当一个线程位于代码的临界区时,另一个线程不进入临界区。如果其他线程试图进入锁定的代码,则它将一直等待(即被阻止),直到该对象被释放。
下面是一个文件的锁工厂:
  /// <summary>  /// 文件锁工厂  /// </summary>  public class LockFactory  {    public object lockObj = new object();    private LockFactory()    {          }    private static LockFactory _lockFactory = new LockFactory();    public static LockFactory Instance    {      get      {        return _lockFactory;      }    }    private IDictionary<string, object> lockDictionary = new Dictionary<string, object>();    public object GetLock(string filename)    {      lock (lockObj)      {        if (lockDictionary.ContainsKey(filename))        {          return lockDictionary[filename];        }        else        {          var obj = new object();          lockDictionary[filename] = obj;          return obj;        }      }    }  }

一般在文件的写,往文件里面追加,删除文件,创建文件,读取文件等等中文件最好是加一下锁。。。

 public class IOLock  {    public static void FileWrite(string filename,string content)    {      lock (LockFactory.Instance.GetLock(filename))      {        File.WriteAllText(filename, content);      }    }    public static void FileAppend(string filename, string content)    {      lock (LockFactory.Instance.GetLock(filename))      {        File.AppendAllText(filename, content);      }    }    public static void DeleteFile(string filename)    {      lock (LockFactory.Instance.GetLock(filename))      {        File.Delete(filename);      }    }    public static void CreateFile(string filename)    {      lock (LockFactory.Instance.GetLock(filename))      {        File.Create(filename).Close();      }    }    public static void CreateFileText(string filename)    {      lock (LockFactory.Instance.GetLock(filename))      {        File.CreateText(filename).Close();      }    }    public static string ReadFileText(string filename)    {      lock (LockFactory.Instance.GetLock(filename))      {        return File.ReadAllText(filename);      }    }  }

View Code

 同一时间只让一个线程访问资源,其他线程等待!