File read/write lock

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.