- Thread Basics
- The Downside
- Implementing Multithreading
- A Demonstration
A Demonstration
Figure 1. The demonstration program's form.
This simple program shows how easy it is to implement multitasking to improve program responsiveness. The code mimics a long calculation or other data processing task with a loop that runs for 10 seconds. You can run this loop either within the program's single default thread, or you can run it in a new thread created using the techniques just described. While the calculations are running you can click a button on the form to display a message box. You'll see a marked difference in how quickly that message box displays with one or two threads.
To create the demo, start a new C# windows Application project. Place four button controls one above the other on the form, with the default names button1 through button 4 top to bottom. Change the captions as shown in the figure.
Next, put the statement
using System.Threading;
at the beginning of the code along with the other using statements. Finally, add the code shown in Listing 1 to the program. When you run the program, it will be very clear how much difference a second thread can make!
Listing 1. Code for the multithreading demo program.
private void button1_Click(object sender, System.EventArgs e) { //Enable/disable buttons. button1.Enabled=false; button2.Enabled=false; button3.Enabled=true; button4.Enabled=false; LongCalculationOneThread(); } private void button2_Click(object sender, System.EventArgs e) { //Enable/disable buttons. button1.Enabled=false; button2.Enabled=false; button3.Enabled=true; button4.Enabled=false; //Run in new thread. AutoResetEvent isDone = new AutoResetEvent(false); ThreadPool.QueueUserWorkItem(new WaitCallback(LongCalculationTwoThreads), isDone); } private void button3_Click(object sender, System.EventArgs e) { MessageBox.Show("You clicked the button!"); } private void button4_Click(object sender, System.EventArgs e) { this.Close(); } private void LongCalculationOneThread() { // Loop for 10 seconds. DateTime t = DateTime.Now; t = t.AddSeconds(10); while (t > DateTime.Now); // Reset buttons. button1.Enabled=true; button2.Enabled=true; button3.Enabled=false; button4.Enabled=true; MessageBox.Show("Calculations finished."); } private void LongCalculationTwoThreads(object state) { // Loop for 10 seconds. DateTime t = DateTime.Now; t = t.AddSeconds(10); while (t > DateTime.Now); //Reset buttons. button1.Enabled=true; button2.Enabled=true; button3.Enabled=false; button4.Enabled=true; // Signal that thread is done. ((AutoResetEvent)state).Set(); MessageBox.Show("Calculations finished."); }