How Can I Synchronize or Lock Multiple Threads in C# to Avoid IOException?

  • Thread starter Thread starter CodeMonkey
  • Start date Start date
  • Tags Tags
    Threads
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 3K views
CodeMonkey
Messages
11
Reaction score
0
I have a server set up which can accept multiple clients in different threads. Now the server keeps track of all client activities using a log feature which writes directly to a txt file. But soemtimes I notice when there are a lot of clients requesting there is an IOException because another process is using the log file. How do I synchronize or lock them? please help. I'm using C#.
 
Physics news on Phys.org
Does your API support semaphores? If so, that is one answer.
There are also file locks - which are maintained by the kernel/filesystem. In windoze
_lock_file does that for you in .NET/framewwork 3.5. see:
http://msdn2.microsoft.com/en-us/library/8w5bsb4f(VS.80).aspx
 
In C# you can synchronize using the lock(){} statement or using the classes: Mutex, Monitor, Semaphore and ReaderWriterLock.

If your threads are also reading from the file at certain times, then use the ReaderWriterLock (enforces single writes, but allows for multiple concurrent reads).

Otherwise, lock (critical section) or Mutex will do, with Mutex being the more CPU intensive option but less prone to deadlocks.

Example:
Code:
public class MyClass{
   private static Mutex MyMutex = new Mutex();
   private static FileInfo MyFile = new FileInfo("myFile.log");
   private static ReaderWriterLock RWLock = new ReaderWriterLock();
   public void DoWork{
       //using a critical section
       //we lock on type because MyFile is static, if it were an instance variable
       //then you would do lock(this){...}
       lock(typeof(MyClass)){
           //write to file
       }
       //using mutex
       MyMutex.WaitOne();
       //write to file
       MyMutex.ReleaseMutex();
       //using read-write lock
       RWLock.AcquireWriterLock();
       //write to file
       RWLock.ReleaseWriterLock();
   }
}
 
Last edited: