Saturday 22 November 2008

Multithreaded Server Development in C#

ThreadPools - typically have a maximum number of threads. If all threads are busy, additional tasks are placed in a queue till one thread becomes available. If no threads are available, create a new set of threads to fill the thread pool. Some classes to consider:

ThreadPool - contains a HostProtectionAttribute (introduced in .NET 2.0). Here is some problem code using ThreadPool.

public static void Main() {
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc)); // Queue task
// Thread.Sleep(1000);
Console.WriteLine("Main thread exits."); }

The code above is bad as the program exits before ThreadProc runs (race condition).

WaitCallback - a callback method (delegate) to be called by a thread pool thread
AutoResetEvent - notifies one waiting thread an event has occurred
ManualResetEvent - notifies one or more waiting threads that an event has occurred.

If there are parts of the server you want to code in C++ you can create a C++ DLL using the Win32 Application Wizard. Here are the options you need to set:
  • Select Application Type->DLL and Additional Options->Export Symbols
  • If calling from non-Unicode code, do Project->Properties (ALT-F7), Configuration Properties->General->Character set (set to use multi-byte character set)
  • ALT-f7 -> Configuration Properties -> C/C++ -> Code Generation -> Runtime Libray: “Multi-threaded Debug (/MTd)”. DLL will statically link to the C runtime library. It will increase the size of the DLL but DLL will not be dependent on the correct version of the C runtime library DLL. This is the default anyway.

No comments: