File read/write lock
To avoid file deadlocks, lock ensures that when one thread is located in the Code critical section, the other thread does not enter the critical section. If other threads attempt to enter the locked code, it waits until the object is released.
Below is a file lock factory:
/// <Summary> /// file lock factory /// </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 ;}}}}
Generally, it is best to add a lock to a file, such as writing a file, appending it to the file, deleting the file, creating the file, and reading the file...
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
Only one thread can access resources at a time. Other threads are waiting!