Wednesday, February 11, 2009

Multithreading in C#

I am reading the book C# 2008, Programmer's Reference, by Wei-Meng Lee. I have just finished the chapter on threading. The book covers the material very well. It does not have a discussion of the process thread pool, but it does cover the different ways to implement multi-threading. The most convenient method is to use the BackgroundWorker component; however, for more advanced threads, the Monitor class is most useful.

The Monitor class has the methods Enter, Exit, Wait and Pulse. They all use an object for locking; use a static object that both threads can access. Use Enter and Exit around the critical section. Use Wait in the event that one thread needs to wait for the other thread to do something before it can continue. The other thread must call pulse when it has completed the task that waiting thread needs to be done.

The lock method is a simple Monitor that only has Enter and Exit.

For some functions, like increment and decrement, there is the Interlock class, which has static methods that are thread safe.

No comments:

Post a Comment

Followers