Starting new Threads is pretty easy, we just need to use one of the Thread constructors, such as
Thread(ThreadStart)
Thread(ParameterizedThreadStart)
There are others, but these are the most common ways to start threads. Lets look at an example of each of these
Code With No Parameters
Thread workerThread = new Thread(StartThread);
Console.WriteLine("Main Thread Id {0}",
Thread.CurrentThread.ManagedThreadId.ToString());
workerThread.Start();
....
....
public static void StartThread()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Thread value {0} running on Thread Id {1}",
i.ToString(),
Thread.CurrentThread.ManagedThreadId.ToString());
}
}
Code With Single Parameter
//using parameter
Thread workerThread2 = new Thread(ParameterizedStartThread);
// the answer to life the universe and everything, 42 obviously
workerThread2.Start(42);
Console.ReadLine();
....
....
public static void ParameterizedStartThread(object value)
{
Console.WriteLine("Thread passed value {0} running on Thread Id {1}",
value.ToString(),
Thread.CurrentThread.ManagedThreadId.ToString());
}
No comments:
Post a Comment