5. November 2011 11:12
In this example we are going to use ThreadSimple to run a background which will happy process "something" until the input arrives. When input arrives in the console application we will aquire the lock which will block the background thread from running. The main idea here is to help give an visual understanding on what a lock between threads is actually doing in an application.
First off lets create a background thread. The only work it is performing is to print a counter to the screen and sleep for 100ms between runs. This uses the ThreadSimple class so you may need to read that post first.
class BackGround : ThreadSimple
{
protected override void Run(object obj)
{
int Counter = 0;
while (true)
{
lock (this)
{
Console.WriteLine("Running ... {0}", Counter);
Counter++;
}
Thread.Sleep(100);
}
}
}
For the foreground thread which is where we are reciving end user input and we are using that to control the execution of the program. The idea here is to wait until return is pressed. Print something out then wait for 5 seconds until the lock is released and then the background thread continues to process what it was doing. Or in short it will present a message to an end user which would be visible for 5 seconds then continue what it was doing.
static void Main(string[] args)
{
BackGround tmp = new BackGround();
tmp.Start();
Console.ReadLine();
lock (tmp)
{
Console.WriteLine("Locking ...");
Thread.Sleep(5000);
Console.WriteLine("UnLocking");
}
Console.ReadLine();
tmp.Stop();
}
When you run the application you should get the following output. With a 5 second delay after "Locking ...."
Running ... 0
Running ... 1
Running ... 2
Running ... 3
Running ... 4
Running ... 5
Running ... 6
Running ... 7
Running ... 8
Locking ...
UnLocking
Running ... 9
Running ... 10
Running ... 11
Running ... 12
Running ... 13
Running ... 14
Running ... 15
f6206ff4-5527-4cbf-ba4f-4b81aa73a694|1|4.0