Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Locking objects and threads

  1. Dec 4, 2007 #1
    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 becuase another process is using the log file. How do I synchronize or lock them? please help. I'm using C#.
  2. jcsd
  3. Dec 4, 2007 #2

    jim mcnamara

    User Avatar
    Science Advisor
    Gold Member

  4. Dec 7, 2007 #3


    User Avatar
    Science Advisor

    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.

    Code (Text):

    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){...}
               //write to file
           //using mutex
           //write to file
           //using read-write lock
           //write to file
    Last edited: Dec 7, 2007
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?

Similar Discussions: Locking objects and threads
  1. Question on Threads (Replies: 1)

  2. Object Recognition (Replies: 10)

  3. Classes and objects (Replies: 6)