- Thread Basics
- The Downside
- Implementing Multithreading
- A Demonstration
Implementing Multithreading
The .Net Framework offers two ways to create a new thread in your program. The remainder of this article explains the simpler of these two methods, the thread pool, which is perfectly adequate for many uses. The .Net runtime maintains a queue of idle threads and assigns them to programs when requested. When the code that the program executes in the thread is complete, the thread is returned to the pool. This is why this method is so simple; the runtime takes care of most of the details for you via the ThreadPool class.
All ThreadPool threads have normal priority, which is what you want when you are using a second thread to improve program responsiveness. The ThreadPool class and all other multithreading-related classes are in the System.Threading namespace.
To create a new thread, call the static ThreadPool.QueueUserWorkItem method. The syntax is as follows:
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadCode), Done);
- ThreadCode is the name of the method in your program where the new thread should start and end executing.
- Done is an AutoResetEvent object that you use to signal the thread pool manager that the program is finished using the thread.
The method specified by the ThreadCode argument must have the proper signature, matching that of the WaitCallback class. Specifically, it must take one argument of type Object and have a void return value. Code in this procedure must also inform the thread pool that it is finished. Here's an example shows a method that meets these two requirements:
static void MyThreadCode(object state) { //Code to be executed by the thread goes here, including //calls to other methods as required. Execution must return //here when complete. //Tell the thread pool that the thread has finished. ((AutoResetEvent)state).Set(); }
You would create this thread and start it running as shown here:
AutoResetEvent IsDone = new AutoResetEvent(false); ThreadPool.QueueUserWorkItem (new WaitCallback(MyThreadCode), IsDone);
Seems too simple to be true, right? Perhaps the following demonstration will convince you!