August 3, 2010 by Christoff Truter C# Threading
Observe the following faulty snippet (don't use):
using System;
using System.Threading;
using System.IO;
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 3; i++)
{
Thread thread = new Thread(new ThreadStart(ThreadMain));
thread.Name = String.Concat("Thread - ", i);
thread.Start();
}
}
static void ThreadMain()
{
// Simulate Some work
Thread.Sleep(500);
// Access a shared resource / critical section
WriteToFile();
}
static void WriteToFile()
{
String ThreadName = Thread.CurrentThread.Name;
Console.WriteLine("{0} using resource", ThreadName);
try
{
using (StreamWriter sw = new StreamWriter("1.txt", true))
{
sw.WriteLine(ThreadName);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
static Mutex mutex = new Mutex();
static void WriteToFile()
{
mutex.WaitOne();
String ThreadName = Thread.CurrentThread.Name;
Console.WriteLine("{0} using resource", ThreadName);
try
{
using (StreamWriter sw = new StreamWriter("1.txt", true))
{
sw.WriteLine(ThreadName);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("{0} releasing resource", ThreadName);
mutex.ReleaseMutex();
}
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
bool createdNew;
using (Mutex mutex = new Mutex(true, "App", out createdNew))
{
if (!createdNew)
{
Console.WriteLine("Application already open");
return;
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
Mutex abandoned prematurely January 14, 2011 by Christoff Truter
An abandoned mutex indicates a serious programming error. http://msdn.microsoft.com/en-us/library/system.threading.abandonedmutexexception.aspx Basically - you're required to explicitly release your mutex before the process that owns the mutex terminates - else it will result in an abandoned mutex exception. Which indicates that the process that owned the mutex might have prematurely ended - crashed etc. (or it was never released in code - but hey .net can't know for sure - so it assumes that something probably went wrong)