Search This Blog

Monday, August 25, 2008

Threading in .net

void DisplayThread1()
{
while (_stopThreads == false)
{
// lock on the current instance of the class for thread #1
lock (this)
{
Console.WriteLine("Display Thread 1");
_threadOutput = "Hello Thread1";
Thread.Sleep(1000);
// simulate a lot of processing
// tell the user what thread we are in thread #1
Console.WriteLine("Thread 1 Output --> {0}", _threadOutput);
} // lock released for thread #1 here
}
}
/// /// Thread 1, Displays that we are in thread 1 (locked) ///
void DisplayThread2()
{
while (_stopThreads == false)
{
// lock on the current instance of the class for thread #2
lock (this)
{
Console.WriteLine("Display Thread 2");
_threadOutput = "Hello Thread2";
Thread.Sleep(1000);
// simulate a lot of processing
// tell the user what thread we are in thread #1
Console.WriteLine("Thread 2 Output --> {0}", _threadOutput);
} // lock released for thread #2 here
}
}

No comments: