Showing posts with label ThreadPool. Show all posts
Showing posts with label ThreadPool. Show all posts

Thursday, August 6, 2009

Another way to pass data into a thread

In the previous thread post I showed a way you can pass information into a thread. Here is another way in which you instantiate the class containing the method you want your thread to call first.
Math math = new Math();
math.Value1 = 1;
math.Value2 = 3;

ThreadPool.QueueUserWorkItem(math.Add);
Now when math.Add is called, it has all the information it needs to do its work.

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