August 6, 2010 by Christoff Truter C# Threading
Observe the following faulty snippet from this post:
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 object locker = new object();
static void WriteToFile()
{
String ThreadName = Thread.CurrentThread.Name;
Console.WriteLine("{0} using resource", ThreadName);
Monitor.Enter(locker);
try
{
using (StreamWriter sw = new StreamWriter("1.txt", true))
{
sw.WriteLine(ThreadName);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Monitor.Exit(locker);
Console.WriteLine("{0} releasing resource", ThreadName);
}
}
static object locker = new object();
static void WriteToFile()
{
String ThreadName = Thread.CurrentThread.Name;
Console.WriteLine("{0} using resource", ThreadName);
lock (locker)
{
try
{
using (StreamWriter sw = new StreamWriter("1.txt", true))
{
sw.WriteLine(ThreadName);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
if (Monitor.TryEnter(locker, 500))
{
try
{
Console.WriteLine("Lock Achieved");
Thread.Sleep(1000); // Simulate work
}
catch
{
throw;
}
finally
{
Monitor.Exit(locker);
}
}
else
{
Console.WriteLine("Lock Failed");
}