Add multi-threading to .NET applications
.NET makes it easy to add multi-threading to your
applications. I assume you know what multi-threading is and only offer an
extremely brief description here. This page does not cover synchronization
or deadlocks. Basically, a thread
is a sequence of execution in a program. Most programs have a single thread and
can do only one thing at a time.
For example, your application calls a method which processes a large amount of
data. While the method runs your application doesn't respond to user input. It
has to wait for the method to complete before it can respond to the mouse or
keyboard. Multi-threading solves this by running the method on its own
worker thread. Windows runs the worker thread for a short
time slice then switches and runs the main thread which responds to
user input. Windows switches context back and forth between threads
until both are complete. Since the time-slice is very short the appearance is
both threads are running simultaneously.
.NET lets you create new threads, suspend, resume and abort
them. The C# sample application illustrates how to do this. The sample executes
a loop that writes messages to a textbox indicating how many iterations of the
loop have executed. Normally, while in the loop the form would not respond to
mouse events. However, when you run the sample you will see the form can still
be dragged and resized while the loop is executing.
This is because the loop is encapsulated in its own method which is run on a
separate thread. Actually, on two threads. By setting the loop counter to a
high value you can see, via the textbox messages, how Windows switches context
between the threads.
You will also note the use of a Delegate to update
the textbox. Controls in Windows Forms are bound to a specific thread and are
not thread safe. Therefore, if you are calling a control's method from a
different thread, you must use one of the control's invoke
methods to marshal the call to the proper thread.
Download the code