Tuesday, July 14, 2009

Make Multi-Threaded Debugging Easier – Name Your Threads !

Writing multi-threaded code isn’t easy (not if you’re doing it properly), but it is becoming more popular, which means more and more often you’ll find yourself debugging multi-threaded code. Here are some tips for making that easier;

1. Name your threads

Unfortunately this is only a good idea if you are manually starting a thread by creating a System.Threading.Thread object… naming a thread that already has a name causes an error and naming a thread pool thread that will be re-used isn’t a good idea.

The idea behind naming your threads is simple… it makes finding them in the debugger (or your log file) easier. Once you’re in a debug session you an open the ‘Threads’ window using the Debug –> Windows –> Threads. This displays a list of all currently running threads, and you can switch the execution thread to another by double clicking on one. The problem is that if you haven’t named your threads, it’s hard to know which is which.

Visual Studio Thread Window

Also, if you have several threads performing the same operation on different sets of data, you can name each one (with a unique name, like “Processing Record XYZ1234” and record the name in any any log entries you make. This will help when reading the log file, as it will allow you to look at only entries from a single thread, and know what that thread was trying to do and which data it was operating on.

To name a thread, just set the name property before starting it;

System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(this.SleepThread));
t.Name = "My Named Thread";

2. Use Background Threads When Appropriate

Often you need to start a thread that runs in the background and waits for some I/O operation. This often involves calling a ‘blocking’ method, such as Receive on a message queue or serial port object. The problem is you don’t want this thread to keep your application open when the main form is closed, and you don’t want to have to write a whole bunch of code to try and kill the thread.

In this case, just set the IsBackground property of the thread before starting it, like so;

System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(this.SleepThread));
t.Name = "My Background Thread";
t.IsBackground = true;

If you do this, .NET will automatically stop the thread when your application closes.

Finally, if you’re serious about multi-threading you should consider;

1. The TPL library available for .NET, which is included in .NET 4

2.  P-Linq

Technorati Tags: ,,,,,

No comments:

Post a comment