Thursday, August 6, 2009

Easiest way to start a thread

The easiest way to start a process on another thread is to call ThreadPool.QueueUserWorkItem.
Example:
// DoSomeWork is a method.
ThreadPool.QueueUserWorkItem(DoSomeWork);
Note: The DoSomeWork method has to have an Object as a parameter.
private static void DoSomeWork(object info)
{
    // Code that does work.
}
If you need to pass data into your method, you can do so:
ThreadPool.QueueUserWorkItem(DoSomeWork, "Info")
You will just have to cast the object back into the appropriate data type.
private static void DoSomeWork(object info)
{
    string workInfo = (string) info;
    // Code that does work.
}


More Info: MSDN: QueueUserWorkItem