Lock
using System;
using System.Threading;
using System.Text;
/*
* This simple thread example demonstrates how to use locks when using threads.
* The program creates a thread in the main() method and runs lockMethod(), it also calls lockMethod()
* on the main thread. We expect the program to print "Finished" twice,but when you run the program,
* it will be printed once and not twice, this
* is becuase of the lock.
* */
class LockDemo
{
private static bool done;
static object locker = new object();
static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(lockMethod));
t.Start(); // Starts the thread to execute lockMethod
lockMethod(); // Calls lockMethod
Console.ReadKey();
}
private static void lockMethod()
{
lock (locker)
{
if (!done)
{
Console.WriteLine("Finished");
done = true;
}
}
}
}
Output:
Finished