Click to Rate and Give Feedback
Related Articles
Here the author introduces SQL Server Data Services, which exposes its functionality over standard Web service interfaces.

By David Robinson (July 2008)
Here the author answers questions regarding the Entity Framework and provides an understanding of how and why it was developed.

By Elisa Flasko (July 2008)
Here we present techniques for programmatic and declarative data binding and display with Windows Presentation Foundation.

By Josh Smith (July 2008)
Systems that handle failure without losing data are elusive. Learn how to achieve systems that are both scalable and robust.

By Udi Dahan (July 2008)
More ...
Articles by this Author
In this month’s installment of .NET Matters, columnist Stephen Toub answers reader questions concerning asynchronous I/O .

By Stephen Toub (July 2008)
This month Stephen Toub discusses asynchronous stream processing.

By Stephen Toub (March 2008)
This month Stephen Toub explains how to make the most of dual processors when running encryption and compression tasks.

By Stephen Toub (February 2008)
The author creates a managed wrapper to use the new IFileOperations interface in Windows Vista from managed code.

By Stephen Toub (December 2007)
Find out how to use finalizers as a way to warn developers who use your custom types when they are garbage collected without having been disposed of correctly.

By Stephen Toub (November 2007)
This month Stephen Toub discusses deadlocks that can occur when synchronizing threads.

By Stephen Toub (October 2007)
Stephen Toub and Shawn Farkas discuss creating an adapter that takes the functionality of RNGCryptoServiceProvider and adapts it to the interface of Random.

By Stephen Toub and Shawn Farkas (September 2007)
Stephen Toub gets nostalgic as he prepares to leave MSDN Magazine.

By Stephen Toub (August 2007)
More ...
Popular Articles
Animating with Silverlight is easier than you think. Here we create a 3D app that folds a polyhedron using XAML, C#, and by emulating the DirectX math libraries.

By Declan Brennan (April 2008)
Here we introduce you to some of the concepts behind the new F# language, which combines elements of functional and object-oriented .NET languages. We then help you get started writing some simple programs.

By Ted Neward (Launch 2008)
Jamie Laflen extols the benefits of TDD when applied to database development—and supplies some useful techniques along the way.

By Jamie Laflen (Launch 2008)
Systems that handle failure without losing data are elusive. Learn how to achieve systems that are both scalable and robust.

By Udi Dahan (July 2008)
More ...
Read the Blog
The most fundamental form of Web testing is HTTP request/response testing. This involves programmatically sending an HTTP request to the Web application, fetching the HTTP response, and examining the response for an expected value. In the May 2008 issue of MSDN Magazine, Read more!
In the November issue of MSDN Magazine, Jeffrey Richter demonstrates some recent additions to the C# programming language that make working with the APM significantly easier. In the June ...
Read more!
The July 2008 issue of MSDN Magazine is now available online. Here's what's in the issue: Data Services: Develop ...
Read more!
The June 2008 issue features the first installment of a new MSDN Magazine column on software design fundamentals. We’ll discuss design patterns and principles in a manner that isn't bound to a specific tool or lifecycle methodology. In this issue, Jeremy Miller starts the Patterns in Practice column ...
Read more!
In the April 2008 issue of MSDN Magazine, Kenny Kerr introduced the Windows Imaging Component (WIC), showing you how you can use it to encode and decode different image ...
Read more!
A combination of the retained-mode graphics system and notification mechanisms such as dependency properties unleash the flexibility and power of Windows Presentation Foundation (WPF, allowing these objects to be targets of data bindings and animations. In the June 2008 issue of MSDN Magazine, Charles ...
Read more!
More ...
.NET Matters
Parameterized ThreadStart, EventWaitHandle, and More
Stephen Toub



Q The ThreadPool.QueueUserWorkItem method lets me pass information to the delegate that will be executed on the worker thread. That's great, but I don't want to use a thread from the pool for this purpose as my scenario really requires a dedicated thread. Unfortunately, the ThreadStart delegate I use to start a new thread is parameterless. How do I pass data to a new thread?
Q The ThreadPool.QueueUserWorkItem method lets me pass information to the delegate that will be executed on the worker thread. That's great, but I don't want to use a thread from the pool for this purpose as my scenario really requires a dedicated thread. Unfortunately, the ThreadStart delegate I use to start a new thread is parameterless. How do I pass data to a new thread?

A There are several common solutions when using the Microsoft® .NET Framework 1.x, and another, easier solution for the .NET Framework 2.0. All of the solutions for the .NET Framework 1.x are variations on the same theme, based on the fact that you can pass to a Thread's constructor a ThreadStart delegate that wraps an instance method of a class. This lets you create a new instance of a class that contains as member variables the state you want to be available to the background thread. That class also contains the entry method for the thread (the method to be wrapped by the ThreadStart delegate). Since this method is part of the same class that contains the relevant state, it has access to the state.
A There are several common solutions when using the Microsoft® .NET Framework 1.x, and another, easier solution for the .NET Framework 2.0. All of the solutions for the .NET Framework 1.x are variations on the same theme, based on the fact that you can pass to a Thread's constructor a ThreadStart delegate that wraps an instance method of a class. This lets you create a new instance of a class that contains as member variables the state you want to be available to the background thread. That class also contains the entry method for the thread (the method to be wrapped by the ThreadStart delegate). Since this method is part of the same class that contains the relevant state, it has access to the state.
With this in mind, Figure 1 shows a general solution to the problem. The WorkerThreadState class contains two data members, a WaitCallback (a delegate with a single object parameter) and an object that represents the state to be passed to the background thread. It also exposes a parameterless public method that simply executes the stored delegate, passing in the background state. Since the Execute method takes no parameters, it can be wrapped in a ThreadStart delegate, and thus it can be used as the entry point with a new Thread. This makeshift solution thus allows you to pass methods to ThreadStart that take a single object parameter, albeit with a riff on the original syntax:
static void Main() {
    string state = "Hello, background world!";
    Thread t = new Thread(new ThreadStart(new WorkerThreadState(
        new WaitCallback(MyMethod), state).Execute));
    t.Start();
}

static void MyMethod(object state) {
    Console.WriteLine("State: " + state);
}
Rather than wrapping MyMethod with a ThreadStart delegate (which can't be done given the difference in signature), MyMethod is wrapped with a WaitCallback (which has the correct signature). That WaitCallback and the state to be supplied to it are wrapped in a new WorkerThreadState, and that WorkerThreadState's parameterless Execute method is wrapped with a ThreadStart delegate. A bit of indirection, to be sure, but it accomplishes the goal. If you're using C# 2.0, you can even take advantage of delegate inference to simplify the call:
Thread t = new Thread(new WorkerThreadState(MyMethod, state).Execute);
Of course, if you're using C# 2.0, you're also using the .NET Framework 2.0, and there's a much simpler solution. The main purpose of a large class library, such as the .NET Framework base class library (BCL), is to provide functionality you can take advantage of in your code. This prevents you and everyone else from having to reinvent the wheel, which helps alleviate code bloat, decreases the amount of code you need to test (since the library has already been tested), and decreases the time to market for your code. Given how frequently used the previous pattern was in applications written for the .NET Framework 1.x, the .NET Framework 2.0 includes a baked-in solution so you don't have to implement a solution like the one in Figure 1. Not only is there a constructor for Thread that accepts a ThreadStart delegate, Thread in the .NET Framework 2.0 exposes another constructor that accepts a ParameterizedThreadStart delegate. ParameterizedThreadStart has the same signature as WaitCallback, and can thus be used with methods that accept a single object parameter. The Thread class's Start method has a parallel overload that accepts an object as a parameter, the state to be passed to the method wrapped with the ParameterizedThreadStart. So, in the .NET Framework 2.0, the previous code snippet could be written simply as:
string state = "Hello, background world!";
Thread t = new Thread(new ParameterizedThreadStart(MyMethod));
t.Start(state);
Again, due to delegate inference, the Thread's creation can be simplified even further:
Thread t = new Thread(MyMethod);
Certainly this is a nice reduction in the amount of code you have to write!
One thing to be careful of when using ParameterizedThreadStart is another constructor now exposed on Thread:
public Thread(ParameterizedThreadStart, int);
If your method wrapped in a ParameterizedThreadStart is expecting an integer as its state, you might inadvertently attempt to pass that state as the second parameter to this constructor, rather than to the Start overload:
int state = 42;
Thread t = new Thread(MyMethod, state);
t.Start();
This will not produce the effect you intend. That second parameter is not the state for Thread, but rather the requested size for the thread's stack. The ability to set a thread's stack size is not new to Win32® developers, as the CreateThread function exposes that capability, but it is new to managed threads with the .NET Framework 2.0. Just because the option is exposed doesn't mean you should use it, though. The default stack size of 1MB should be appropriate for almost any application you're developing. If it's not, chances are you have a bug or poor design in your code. That said, there are valid circumstances where you might want to change the stack size.
An easy way to see the effect of this parameter is to create and start as many threads as you can. Suppose you have two gigabytes of virtual address space. If all of that space is available for thread creation and if each thread reserves 1MB of memory, you should be able to create around 2000 threads. Figure 2 shows a simple test harness for counting the number of threads that can be created and started with a specific stack size. Sure enough, calling it three times with starting stack sizes of 512KB, 1MB, and 2MB, respectively, yields the following output:
After 3828 threads: OutOfMemoryException
After 1917 threads: OutOfMemoryException
After 956 threads: OutOfMemoryException
I can't think of any scenarios in which you'd want to create so many threads; it would almost certainly wreck your performance. The point here is that changing the stack size of each thread changes the number of threads you can create, which is limited by available memory.

Q I have two String variables referencing two different String instances. I'd like to query the first variable for the String it references, while at the same time copying the reference from the second String variable to the first. The trouble is that I'm doing this in a concurrent application, and I want to make sure this set of operations is atomic. The Interlocked.Exchange method seems to be exactly what I need, but the compiler complains when I try to use this overload:
object Exchange(ref object location1, object value1);
The error I receive from the compiler states that it can't convert from "ref string" to "ref object". Why not? And if that's not possible, what good is Interlocked.Exchange?
Q I have two String variables referencing two different String instances. I'd like to query the first variable for the String it references, while at the same time copying the reference from the second String variable to the first. The trouble is that I'm doing this in a concurrent application, and I want to make sure this set of operations is atomic. The Interlocked.Exchange method seems to be exactly what I need, but the compiler complains when I try to use this overload:
object Exchange(ref object location1, object value1);
The error I receive from the compiler states that it can't convert from "ref string" to "ref object". Why not? And if that's not possible, what good is Interlocked.Exchange?

A Think about the contract you're creating when you author a method with a pass-by-reference parameter (signaled by the ref keyword in C#). For example, consider the following method:
void DoSomething(ref object data)
{
    data = "a string";
    data = 42;
    data = WebRequest.Create("http://msdn.microsoft.com/msdnmag");
}
In this code, the data argument can be set to anything at all within the body of DoSomething. It could be set to a string, a boxed integer, an HttpWebRequest, or anything else that is or that derives from System.Object, which in .NET is pretty much everything. This means that the variable passed by reference to this method must be capable of holding any managed type, since the method could attempt to store any type of object into it. And since the type safety rules of .NET prevent a variable of a certain type from storing a value or a reference to an object of an incompatible type (one that isn't the same type or that derives from that type), the variable you pass by reference to DoSomething must be capable of storing an instance of any type. The only type in the .NET Framework that fits that bill is System.Object.
A Think about the contract you're creating when you author a method with a pass-by-reference parameter (signaled by the ref keyword in C#). For example, consider the following method:
void DoSomething(ref object data)
{
    data = "a string";
    data = 42;
    data = WebRequest.Create("http://msdn.microsoft.com/msdnmag");
}
In this code, the data argument can be set to anything at all within the body of DoSomething. It could be set to a string, a boxed integer, an HttpWebRequest, or anything else that is or that derives from System.Object, which in .NET is pretty much everything. This means that the variable passed by reference to this method must be capable of holding any managed type, since the method could attempt to store any type of object into it. And since the type safety rules of .NET prevent a variable of a certain type from storing a value or a reference to an object of an incompatible type (one that isn't the same type or that derives from that type), the variable you pass by reference to DoSomething must be capable of storing an instance of any type. The only type in the .NET Framework that fits that bill is System.Object.
Interlocked.Exchange suffers from the same burden. Its first parameter is an object reference passed by reference, and Exchange needs to be able to set this to an instance of any type, especially since half the purpose of Exchange is to set this parameter equal to the second parameter, and the second parameter can be anything (since it's of type System.Object). Thus, the first parameter passed by reference to Exchange must be of type System.Object, nothing more and nothing less (there is nothing less). In the .NET Framework 1.x this makes Interlocked.Exchange useless for variables with types other than the core numerical types like System.Int32 (each of which have their own Exchange overloads) and System.Object itself.
The .NET Framework 2.0 helpfully addresses this limitation with a new generic overload of Interlocked.Exchange:
public static T Exchange<T>(ref T location1, T value) where T: class
This overload lets you do exactly what you want:
private string str1 = ...;
private string str2 = ...;
...
string oldStr1Value = Interlocked.Exchange<string>(ref str1, str2);
And through the magic of type inference, the C# compiler allows you to omit generic type parameters where they can be inferred from method arguments. Thus, you could simply use:
string oldStr1Value = Interlocked.Exchange(ref str1, str2);
As an aside, I've heard several rumblings from the general development community that generics are good for little more than collections. This is a perfect example of how generics can be used to solve a number of problems unrelated to collections.

Q I noticed that there's a new EventWaitHandle class in the .NET Framework 2.0. How does this differ from AutoResetEvent and ManualResetEvent?
Q I noticed that there's a new EventWaitHandle class in the .NET Framework 2.0. How does this differ from AutoResetEvent and ManualResetEvent?

A Win32 exposes manual-reset and auto-reset events as a single type of event object, created using the CreateEvent function. This function accepts a Boolean bManualReset argument, which dictates whether the ResetEvent function must be used to change the event object to a nonsignaled state or whether the object is automatically reset to a nonsignaled state after a single waiting thread has been released. For the .NET Framework 1.x, this functionality was split into two separate managed classes, AutoResetEvent and ManualResetEvent, which simply wrap CreateEvent, supplying the appropriate bManualReset argument. Like Mutex, both AutoResetEvent and ManualResetEvent derived from WaitHandle, obscuring their relationship and leaving only their names to suggest their shared heritage.
A Win32 exposes manual-reset and auto-reset events as a single type of event object, created using the CreateEvent function. This function accepts a Boolean bManualReset argument, which dictates whether the ResetEvent function must be used to change the event object to a nonsignaled state or whether the object is automatically reset to a nonsignaled state after a single waiting thread has been released. For the .NET Framework 1.x, this functionality was split into two separate managed classes, AutoResetEvent and ManualResetEvent, which simply wrap CreateEvent, supplying the appropriate bManualReset argument. Like Mutex, both AutoResetEvent and ManualResetEvent derived from WaitHandle, obscuring their relationship and leaving only their names to suggest their shared heritage.
EventWaitHandle remedies this in the .NET Framework 2.0. A concrete class, EventWaitHandle contains all of the functionality (and more) that AutoResetEvent and ManualResetEvent exposed in .NET Framework 1.x. All of EventWaitHandle's public constructors accept an argument of type EventResetMode:
public enum EventResetMode {
    AutoReset, ManualReset
}
Just like the bManualReset argument to CreateEvent, the EventResetMode tells the new EventWaitHandle whether to act as a manual-reset or an auto-reset event object. AutoResetEvent and ManualResetEvent now both derive from EventWaitHandle, highlighting their relationship as siblings. In fact, these two classes now contain nothing more than constructors used to pass the appropriate EventResetMode to their base class's constructor:
public sealed class AutoResetEvent : EventWaitHandle
{
    public AutoResetEvent(bool initialState) : 
        base(initialState, EventResetMode.AutoReset) {}
}

public sealed class ManualResetEvent : EventWaitHandle
{
    public ManualResetEvent(bool initialState) : 
        base(initialState, EventResetMode.ManualReset) {}
}
If you're using AutoResetEvent or ManualResetEvent in code you're upgrading to the .NET Framework 2.0, don't fret about this change. Unless your code is using reflection to examine the immediate base class and will freak out if it finds something other than WaitHandle, you should be fine. In the .NET Framework 1.x, the only public methods exposed from AutoResetEvent and ManualResetEvent were Set and Reset, and both of these are available on EventWaitHandle with the exact same signature. Your code should compile and run just fine.
EventWaitHandle is more than just the result of refactoring. It exposes several frequently asked-for features not provided in the .NET Framework 1.x. This new functionality is best exemplified by one of the public constructors on EventWaitHandle:
public EventWaitHandle(
    bool initialState, EventResetMode mode, 
    string name, out bool createdNew, 
    EventWaitHandleSecurity eventSecurity);
The initialState parameter serves the same purpose as it does with AutoResetEvent and ManualResetEvent, determining whether the initial state of the event is signaled or nonsignaled, and the mode parameter determines the type of the event, as already discussed. The third parameter, name, allows for the creation of named events. Specifying null for this parameter reverts to the same unnamed event functionality available in the .NET Framework 1.x. But specifying a non-null string allows you to create non-local events, events that are systemwide and that can be accessed by other processes on the machine (in the .NET Framework 1.x, named synchronization primitives like this were available only in the form of a Mutex). This lets you coordinate resource usage across process boundaries. You can open an existing named event using the static EventWaitHandle.OpenExisting method, but you can also use the EventWaitHandle constructor. When you create a named event, the fourth parameter (the createdNew output Boolean) will tell you whether you created a new event with this name or opened an existing event with the same name.
The final parameter, eventSecurity, hints at a new feature that spans all of the kernel objects exposed through the .NET Framework 2.0: the ability to use Windows® access control security with named kernel objects. With this feature you can restrict which users on the system have access to the named event, as well as what they're able to do with it. It also gives you control over security auditing on the event.

Q I'm writing a class library that needs to perform some work asynchronously. I want to fire off some events from the background thread doing the actual work, but I want the event handlers for the event to be raised on an appropriate thread for the current execution environment. So, for example, if the library is being used in a Windows Forms-based application, I'd like the events to be raised on the UI thread. How can my library determine the environment and then do this marshaling correctly?
Q I'm writing a class library that needs to perform some work asynchronously. I want to fire off some events from the background thread doing the actual work, but I want the event handlers for the event to be raised on an appropriate thread for the current execution environment. So, for example, if the library is being used in a Windows Forms-based application, I'd like the events to be raised on the UI thread. How can my library determine the environment and then do this marshaling correctly?

A For Windows Forms, you'd typically use the ISynchronizeInvoke interface of one of the controls created on the UI thread. This would marshal the call to the UI thread, making the executed method safe for UI control manipulation. Of course, if you don't have a reference to a valid control, as might be the case in a library you're writing for use in a variety of contexts, it is more difficult to use this technique.
A For Windows Forms, you'd typically use the ISynchronizeInvoke interface of one of the controls created on the UI thread. This would marshal the call to the UI thread, making the executed method safe for UI control manipulation. Of course, if you don't have a reference to a valid control, as might be the case in a library you're writing for use in a variety of contexts, it is more difficult to use this technique.
The .NET Framework 2.0 introduces the SynchronizationContext class to address this and related scenarios. You can think of SynchronizationContext as ISynchronizeInvoke on steroids, providing the same functionality but at a higher level of abstraction, allowing it to work with environments other than Windows Forms. SynchronizationContext provides two methods you'll use most frequently, Send and Post. Send corresponds to ISynchronizeInvoke.Invoke, while Post corresponds to ISynchronizeInvoke.BeginInvoke. The idea here is that from your library, you can retrieve the current SynchronizationContext from the SynchronizationContext.Current static property. You can then use its Post or Send method to marshal your invocation to the proper thread.
Though not abstract, SynchronizationContext by itself isn't all that useful. The default implementation of the Send and Post methods are as follows:
public virtual void Send(SendOrPostCallback d, object state)
{
      d(state);
}

public virtual void Post(SendOrPostCallback d, object state)
{
      ThreadPool.QueueUserWorkItem(new WaitCallback(d.Invoke), state);
}
public delegate void SendOrPostCallback(object state); Both Send and Post accept a SendOrPostCallback (a delegate with a single object parameter) and an object instance to be supplied to the target method. The default implementation of Send simply invokes the delegate, passing to it the state object. The default implementation of Post simply queues the delegate and the state to the ThreadPool. Not very interesting. What is interesting is that both of these methods are virtual, the idea being that specialized SynchronizedCallback-derived classes will be created for each environment that has specific needs when it comes to synchronizing invocations across threads.
Windows Forms is, of course, one such environment. It provides a class derived from SynchronizationContext: WindowsFormsSynchronizationContext. (Tricky, huh?) An instance of WindowsFormsSynchronizationContext is created before the application's main message loop is started and is stored into the ExecutionContext for the UI thread (instances of WindowsFormsSynchronizationContext may also be created when controls are instantiated from non-UI threads). When instantiated, WindowsFormsSynchronizationContext queries the current Application's thread context for the control to use for marshaling. It uses this control in its overrides of Send and Post, which look something like the following:
public override void Send(SendOrPostCallback d, object state)
{
    controlToSendTo.Invoke(d, new object[] { state });
}
public override void Post(SendOrPostCallback d, object state)
{
    controlToSendTo.BeginInvoke(d, new object[] { state });
}
As you can see, WindowsFormsSynchronizationContext handles all of the marshaling for you. So, if your library will be executing some code on a background thread and needs to marshal some code to a safe UI context, all you need to do is retrieve the current WindowsFormsSynchronizationContext, store it, and then from the background thread use either Post or Send. This is exactly what the BackgroundWorker component does.
BackgroundWorker is a new class in the .NET Framework 2.0 that makes it easy to execute long-running tasks from a background thread, executing progress updates and completion notifications on the UI thread. You register with the BackgroundWorker instance's DoWork event a DoWorkEventHandler for the code you want to be run on the background thread. You can then also register event handlers with the ProgressChanged and RunWorkerCompleted events. To start the background task running, you use the RunWorkerAsync method. Before using delegate asynchronous invocation to start the background task, however, BackgroundWorker retrieves and stores the current SynchronizationContext (though not directly, but rather through AsyncOperationManager.CreateOperation, which indirectly wraps SynchronizationContext.Current). The code running on the background thread uses the ReportProgress method to execute code back on the UI thread; under the covers, BackgroundWorker is simply using the stored SynchronizationContext and its Post method to marshal the call.
Windows Forms isn't the only environment that provides a SynchronizationContext-derived class. ASP.NET also provides one, AspNetSynchronizationContext, though it's not public and is not meant for external consumption. Rather, it is used under the covers by ASP.NET to facilitate the asynchronous pages functionality in ASP.NET 2.0 (for more information, see msdn.microsoft.com/msdnmag/issues/05/10/WickedCode). This implementation allows ASP.NET to prevent page processing completion until all outstanding asynchronous invocations have been completed.

Send your questions and comments to  netqa@microsoft.com.


Stephen Toub is the Technical Editor for MSDN Magazine.

Page view tracker