Friday, January 30, 2015

Protect Data on Multiple Processes using C#

If you have a routine which splits data across processors using the Parallel class you may need to protect memory, files or other resources which are shared across the multiple processes. One solution to this is to use a mutex, which is similar to a Monitor object, but at the operating system level. Mutexes must be named to ensure that both processes can open the exact same mutex object.
The below sample uses a mutex to protect a file from being written to by two instances of this same program:
static void Main(string[] args)
{
Mutex mutexObj = new Mutex(false, “MutexDemo1”);
Process me = Process.GetCurrentProcess();
string outputFile = “MutexDemoOutput1.txt”;
while (!Console.KeyAvailable)
{
mutexObj.WaitOne();
Console.WriteLine(“The process {0} gained control”, me.Id);
using (FileStream fsObj = new FileStream(outputFile,
FileMode.OpenOrCreate))
using (TextWriter writer = new StreamWriter(fsObj))
{
fsObj.Seek(0, SeekOrigin.End);
string outputObj = string.Format(“The process {0} writing timestamp
 {1}”, me.Id, DateTime.Now.ToLongTimeString());
writer.WriteLine(outputObj);
Console.WriteLine(outputObj);
}
Console.WriteLine(“The process {0} releasing control”, me.Id);
mutexObj.ReleaseMutex();
Thread.Sleep(1000); }
}
As with a Monitor object, you may attempt a wait on a mutex for a TimeSpan before giving up, and in case the mutex gives up WaitOne will return false.
In the above code, each process will lock the mutex before then writing to the file. Ensure you select good names for your mutexes, you should either use a unique combination of your application, company, and mutex purpose, or else use a GUID to make sure no collisions with your own applciations or others.

No comments:

Post a Comment