Jul 04

Multithreading: a final example on how CompareExchange might help you

Posted in C# Multithreading      Comments Off on Multithreading: a final example on how CompareExchange might help you

In the last posts we’ve been poking around memory models, memory fences and other interesting things that might lead to the so called lock free programming. Before keep looking at how we can use those features from our C# code, I’d like to add one more example that shows how the interlocked operations might help you in the real world. Do you recall our implementation of the IAsyncResult interface?

At the time, we’ve used a lock for ensuring proper access and initialization of our manual reset event used for signaling the end of the operation. Now that we’ve met interlocked operations, we can improve that code and get rid of the lock. Let’s focus on the private GetEvtHandle method:

private ManualResetEvent GetEvtHandle() {
  var newEvt = new ManualResetEvent(false);
  if (Interlocked.CompareExchange(ref _evt, newEvt, null) != null) {
  if (_isCompleted) {
  return _evt;

As you can see, we’ve replaced the lock with a CompareExchange method call for ensuring proper atomic update: if the _evt field is null, then set it to newEvt (which, if you recall our previous post on interlocked operations, will only happen when that value is null!). Since the method returns the old value, if we get anything different from null,then it means that some other thread already set the field to a valid value. When that happens,we need to clean up and close the manual reset event we’ve just created. And there you go: the lock is gone.

As you’ve probably guessed, This strategy can be adjusted to objects that implement the IDisposable interface and you can use it when the creation of new objects isn’t too expensive and you need to have only a single instance of an item (in other words, it might be a valid option for implementing singletons in multithreading scenarios).

And that’s it. Keep tuned for more on multithreading.