Creating threads in VS.NET is much easier than in previous Visual Studio languages. Here is an introduction on how to create a thread and have it execute a function in C#
First you must reference the thread functions
Code:
using System.Threading;
The code we want to run on our thread
Code:
protected void DoSomethingOnAThread()
{
string s ;
s = "This is output from another thread";
Console.WriteLine(s);
}
To start our thread and have it execute the above function
Code:
thread = new Thread(new ThreadStart( DoSomethingOnAThread ));
thread.Start();
Now our function will be called by the new thread. When the function exits the thread will be terminated.
To set the windows priority of the thread use the following constants:
Normal,
AboveNormal,
BelowNormal,
Highest, and
Lowest Code:
thread.Priority = ThreadPriority.Highest;
To kill a thread, see if it is really running and then call the abort method on the thread
Code:
if ( thread.IsAlive )
{
thread.Abort();
}
You can pause a thread for a fixed length of time. If you specify 0 as the time, the thread is suspended and will let any other threads run. If you specify the
Infinit constant the thread will be blocked indefinitely. The function take an integer as the milliseconds to sleep or a
Timespan variable
Code:
thread.Sleep(10);
To suspend a thread use
Code:
if (thread.ThreadState = ThreadState.Running)
{
thread.Suspend();
}
To resume a suspended thread
Code:
if (thread.ThreadState = ThreadState.Suspended)
{
thread.Resume();
}
Threading has many benifits:
- You can process long tasks in the background
- You can make a user interface look better by not locking it when the user clicks something. This gives the feel of a fast well working user interface. An example of this is MS word. When you save a document you get a little icon on the status bar that shows a disk and a progress bar of the save. While it is saving you can cotinue to work
- You could do network comunications over a different thread and have users doing other things while waiting on data
Threads also have some pitfalls:
- If you have a large number of threads, it can hurt performance while the OS switches between them
- The more threads you have the more memory your app needs
- Many threads can be a big source of bugs
- Killing threads means you have to know exactly what will happen if you kill the thread.
- If you have variables that are accessed by more than one thread you have to make sure you have a good variable locking plan
John Spano
President
NeoTekSystems, Inc.
www.NeoTekSystems.com
MCSD, MCTS-Windows, MCTS-Web, MCPD-Distributed, MCITP-SQLDev, MCITP-SQLAdmin