Home > .NET Framework > A cross process synchronization – Mutex

A cross process synchronization – Mutex

Let us take the same Logger class. Assume the library is used by multiple processes, That would still result in out-of order execution. How can we synchronize across processes? The Mutex class comes to our rescue. The Logger example rewritten using a mutex is given below:
public class Logger {
    private static StreamWriter writer;
    private static Mutex writerLock;
    static Logger() {
        // read fileName from config or something else
        writer = new StreamWriter(fileName);
        writerLock = new Mutex(false, "Global\WriterLock");
    }
    public static void Log(string source, string category, string message) {
        try {
            writerLock.WaitOne();
            writer.WriteLine("—————————————————————————-");
            writer.WriteLine("Source: " + source);
            writer.WriteLine("Date & Time: " + DateTime.Now.ToString("dd/MM/yyyy HH:mm"));
            writer.WriteLine("Category: " + category);
            writer.WriteLine("Message: " + message);
            writer.WriteLine("—————————————————————————-");
        }
        finally {
           writerLock.ReleaseMutex();
        }
    }
}
This is similar to the Monitor.Enter and monitor.Leave. WaitOne checks to see if another thread owns the mutex. If not this thread can enter the critical section and becomes the owner of the mutex. If another thread owns the mutex the calling thread is put into a WaitSleepJoin state and remains in that state till the original owner of the mutex call ReleaseMutex.

Advertisements
Categories: .NET Framework
  1. Unknown
    November 23, 2008 at 10:06 am

    您需要二手液晶显示屏、废旧液晶屏么?我们是不折不扣的二手液晶屏、旧液晶屏大批发商,长期大量供应可再利用的旧液晶屏。我公司提供的各种尺寸的二手液晶屏, 不同厚薄如笔记本屏,均已经过我们严格的分类,检验,测试流程。请访问协力液晶屏www.sceondhandlcd.com[bbibageghaabcbbi]

  1. November 19, 2010 at 10:59 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: