DelegateMarshaler – Replace Control.InvokeRequired and Control.Invoke

Tuesday, July 22nd, 2008

EDIT (12/6/2014): If you like C#, WPF, 3D, and Golf, check out my latest side project: https://www.youtube.com/watch?v=8pWq8vhZqbg
If you don’t like golf, don’t click the link!

This is the third visitation of the topic of UI and worker thread interaction. Based upon excellent feedback through the comments (thanks Peter Ritchie and others) I have renamed and modified the previous ThreadBarrier implementation (which was a poor name to begin with since a thread barrier concept already represents something else). The previous pattern of encapsulating a thread and communicating to the UI via events raised on the UI thread is still my recommendation: see the first post for a long winded explanation, and the second post for more examples. However, there are many people that already have existing code that uses the Control.InvokeRequired and Control.Invoke pattern such as:

delegate void UpdateProgressDelegate(int progress);

 

public void UpdateProgressBar(int progress)

{

if (this.InvokeRequired == false)

{

this.progressBarDownload.Value = progress;

}

else

{

this.Invoke(new UpdateProgressDelegate(UpdateProgressBar), new object[] { progress });

}

}

The new implementation is intended to replace this code and support the original ThreadBarrier concept.

Introducing the DelegateMarshaler

The DelegateMarshaler implementation is virtually identical to the ThreadBarrier except for four minor differences:

  1. The marshaler is created using a static method DelegateMarshaler.Create() so an exception can be thrown if no SynchronizationContext exists (console app, or before UI is started, etc.)
  2. If the calling thread is already the target thread (UI thread), then the delegate is invoked normally rather than a cross thread invoke. This is similar to InvokeRequired being false.
  3. The DelegateMarshaler supports methods with 0 to 4 arguments.
  4. Static methods wrap ThreadPool.QueueUserWorkItem in a type safe way.

A compact example

void buttonDownload_Click(object sender, EventArgs e)

{

DelegateMarshaler marshaler = DelegateMarshaler.Create();

 

DelegateMarshaler.QueueOnThreadPoolThread(

(fileName) =>

{

//simulate download

for (int i = 0; i < 100; ++i)

{

marshaler.Invoke(UpdateProgressBar, i);

Thread.Sleep(50);

}

marshaler.Invoke(ShowDownloadComplete, fileName);

},

“somefile.txt”);

}

 

private void UpdateProgressBar(int progress)

{

this.progressBarDownload.Value = progress;

}

 

private void ShowDownloadComplete(string fileName)

{

this.labelFileDownload.Text = fileName;

}

Using the DelegateMarshaler consists of creating the marshaler on the UI thread and invoking the methods that update the UI (preferably from the worker thread). Invoke will call the method synchronously, and BeginInvoke will call the method asynchronously allowing the worker to continue running while the UI updates. If your thread is a separate method altogether (which is usually the case), you would want to save the DelegateMarshaler instance as a private field in your form or control so it can be used in the thread method.

The DelegateMarshaler Implementation

public sealed class DelegateMarshaler

{

private SynchronizationContext _synchronizationContext;

 

public static DelegateMarshaler Create()

{

if (SynchronizationContext.Current == null)

{

throw new InvalidOperationException(“No SynchronizationContext exists for the current thread.”);

}

return new DelegateMarshaler(SynchronizationContext.Current);

}

 

private DelegateMarshaler(SynchronizationContext synchronizationContext)

{

this._synchronizationContext = synchronizationContext;

}

 

private bool IsMarshalRequired

{

get

{

return this._synchronizationContext != SynchronizationContext.Current;

}

}

 

public void Invoke<T>(Action<T> action, T arg)

{

if (this.IsMarshalRequired == false)

{

// already on the target thread, just invoke delegate directly

action(arg);

}

else

{

// marshal the delegate call to the target thread

this._synchronizationContext.Send(delegate { action(arg); }, null);

}

}

 

//simplifies use of threadpool so arguments do not need to be cast

public static void QueueOnThreadPoolThread<T>(Action<T> action, T arg)

{

ThreadPool.QueueUserWorkItem(delegate { action(arg); });

}

}

It is such a small class, feel free to modify it to fit your needs. Download the sample for the complete code and comments:

DelegateMarshalerSample

Notable Links
http://thevalerios.net/matt/2008/05/a-type-safe-backgroundworker-wrapper/
http://weblogs.asp.net/justin_rogers/articles/126345.aspx
http://www.codeproject.com/KB/cs/AOPInvokeRequired.aspx

kick it on DotNetKicks.com

Simplifying UI and Worker Threads – DelegateMarshaler Revisited

Tuesday, July 22nd, 2008

EDIT (12/6/2014): If you like C#, WPF, 3D, and Golf, check out my latest side project: https://www.youtube.com/watch?v=8pWq8vhZqbg
If you don’t like golf, don’t click the link!

Background

Update – ThreadBarrier was a poorly chosen name, use the latest DelegateMarshaler implementation instead.

Previously I introduced the ThreadBarrier pattern which describes a simple technique for allowing worker threads to easily and safely communicate with controls on the UI thread. The key points from the previous article are:

A worker thread is completely contained within a class (and any objects the class references)

  1. Events from this worker class are raised on the UI thread
  2. A SynchronizationContext is used rather than Control.Invoke or Dispatcher.Invoke
  3. The UI code does not have to worry about what thread is executing, it always assumes the UI thread (keeps code clean)
  4. The ThreadBarrier needs to be created on a UI thread to capture the UI’s SynchronizationContext

Today’s article is a revisitation of the pattern to demonstrate several ways the technique can be used, as well as describe the flaw in the previous implementation. Yesterday’s article on events and threads provides an in depth background on the subtleties of events and multithreading. The contents of today’s post include:

  • The New ThreadBarrier Code
  • Sample UI and Worker Classes
  • ThreadBarrier Technique #1: Subclassing an existing worker thread class
  • ThreadBarrier Technique #2: Using extension methods on a SynchronizationContext
  • ThreadBarrier Technique #3: Deriving from a ThreadBarrier
  • ThreadBarrier Technique #4: Creating an instance of a ThreadBarrier
  • ThreadBarrier Technique #5: Creating an adapter class to propagate events
  • The Original ThreadBarrier Implementation Flaw
  • ThreadBarrier FAQ

Download the examples.

The New ThreadBarrier Code

.NET 2.0

public class ThreadBarrier

{

private SynchronizationContext _synchronizationContext;

 

public ThreadBarrier()

{

this._synchronizationContext = AsyncOperationManager.SynchronizationContext;

}

 

public void Post<T>(Action<T> raiseEventMethod, T e)

where T : EventArgs

{

if (this._synchronizationContext == null)

{

ThreadPool.QueueUserWorkItem(delegate { raiseEventMethod(e); });

}

else

{

this._synchronizationContext.Post(delegate { raiseEventMethod(e); }, null);

}

}

}

.NET 3.5

public static class ThreadBarrierExtensions

{

public static void Post<T>(this SynchronizationContext synchronizationContext, Action<T> raiseEventMethod, T eventArgs)

where T : EventArgs

{

if (synchronizationContext == null)

{

ThreadPool.QueueUserWorkItem((e) => raiseEventMethod((T)e), eventArgs);

}

else

{

synchronizationContext.Post((e) => raiseEventMethod((T)e), eventArgs);

}

}

}

The use of an anonymous delegate can be used for either implementation. The .NET 3.5 version uses a lambda expression just to demonstrate an alternate way of invoking the action.

Sample UI and Worker Classes

The sample UI and worker classes are very simple examples that will be the reference code for the techniques that follow. The UI code remains virtually unchanged throughout every technique which is ideal since it should not be concerned with threading:

These classes do not work together as is, they need a ThreadBarrier.

Sample Worker Class

public class WeatherChecker

{

public event EventHandler<WeatherEventArgs> TemperatureChanged;

public event EventHandler<WeatherEventArgs> HumidityChanged;

public event EventHandler<WeatherEventArgs> WindChanged;

public event EventHandler Stopped;

 

private bool _isStopRequested;

private Random _random;

 

public WeatherChecker()

{

this._isStopRequested = false;

 

//used for generating random weather information

this._random = new Random((int)DateTime.Now.Ticks);

}

 

public void Start()

{

Thread thread = new Thread(new ThreadStart(CheckWeather));

thread.IsBackground = true; //prevents thread from keeping app alive when app is closed

thread.Start();

}

 

private void CheckWeather()

{

while (this._isStopRequested == false)

{

OnTemperatureChanged(new WeatherEventArgs(Rand(30f)));

OnWindChanged(new WeatherEventArgs(Rand(15f)));

OnHumidityChanged(new WeatherEventArgs(Rand(100f)));

 

//Updates roughly 4 times per second

Thread.Sleep(250);

}

 

OnStopped(EventArgs.Empty);

}

 

public void RequestStop()

{

this._isStopRequested = true;

}

 

private float Rand(float max)

{

return (float)this._random.NextDouble() * max;

}

 

protected virtual void OnTemperatureChanged(WeatherEventArgs e)

{

if (this.TemperatureChanged != null)

{

this.TemperatureChanged(this, e);

}

}

protected virtual void OnHumidityChanged(WeatherEventArgs e)

{

if (this.HumidityChanged != null)

{

this.HumidityChanged(this, e);

}

}

protected virtual void OnWindChanged(WeatherEventArgs e)

{

if (this.WindChanged != null)

{

this.WindChanged(this, e);

}

}

protected virtual void OnStopped(EventArgs e)

{

if (this.Stopped != null)

{

this.Stopped(this, e);

}

}

}

Sample UI Class

public partial class Form1 : Form

{

private WeatherChecker _weatherChecker;

 

public Form1()

{

InitializeComponent();

}

 

private void buttonStart_Click(object sender, EventArgs e)

{

this.buttonStart.Enabled = false;

this.buttonStop.Enabled = true;

 

this._weatherChecker = new WeatherChecker();

this._weatherChecker.TemperatureChanged += new EventHandler<WeatherEventArgs>(_weatherChecker_TemperatureChanged);

this._weatherChecker.HumidityChanged += new EventHandler<WeatherEventArgs>(_weatherChecker_HumidityChanged);

this._weatherChecker.WindChanged += new EventHandler<WeatherEventArgs>(_weatherChecker_WindChanged);

this._weatherChecker.Stopped += new EventHandler(_weatherChecker_Stopped);

 

this._weatherChecker.Start();

}

 

private void buttonStop_Click(object sender, EventArgs e)

{

this._weatherChecker.RequestStop();

}

 

void _weatherChecker_TemperatureChanged(object sender, WeatherEventArgs e)

{

this.labelTemperature.Text = String.Format(“{0:F1} C”, e.Value);

}

 

void _weatherChecker_HumidityChanged(object sender, WeatherEventArgs e)

{

this.labelHumidity.Text = String.Format(“{0:F0}%”, e.Value);

}

 

void _weatherChecker_WindChanged(object sender, WeatherEventArgs e)

{

this.labelWind.Text = String.Format(“{0:F0} mph”, e.Value);

}

 

void _weatherChecker_Stopped(object sender, EventArgs e)

{

this.buttonStop.Enabled = false;

this.buttonStart.Enabled = true;

 

this._weatherChecker = null;

}

}

ThreadBarrier Technique #1: Subclassing an existing worker thread class

The two classes above are doing nothing special to communicate with on another. An attempt to use the two together would fail since the worker class is raising events on the worker thread which is not allowed to access controls on the UI thread. Amazingly using a ThreadBarrier in the following way causes all events from the worker class to be automatically raised on the UI thread:

public class ThreadBarrierWeatherChecker : WeatherChecker

{

private ThreadBarrier _threadBarrier;

 

public ThreadBarrierWeatherChecker()

{

this._threadBarrier = new ThreadBarrier();

}

 

protected override void OnTemperatureChanged(WeatherEventArgs e)

{

this._threadBarrier.Post(base.OnTemperatureChanged, e);

}

 

protected override void OnWindChanged(WeatherEventArgs e)

{

this._threadBarrier.Post(base.OnWindChanged, e);

}

 

protected override void OnHumidityChanged(WeatherEventArgs e)

{

this._threadBarrier.Post(base.OnHumidityChanged, e);

}

 

protected override void OnStopped(EventArgs e)

{

this._threadBarrier.Post(base.OnStopped, e);

}

}

That’s it! All it took was deriving from the worker class and posting the method that raises the events to the UI thread. The UI class should create an instance of ThreadBarrierWeatherChecker rather than WeatherChecker. This technique is handy if you do not own or can’t modify the code to the worker class.

ThreadBarrier Technique #2: Using extension methods on a SynchronizationContext

This technique requires the developer to not only have access to the WeatherChecker code, but also capture the UI’s SynchronizationContext in the WeatherChecker’s constructor:

private SynchronizationContext _synchronizationContext;

 

public WeatherChecker()

{

this._synchronizationContext = AsyncOperationManager.SynchronizationContext;

}

Raising events now uses the _synchronizationContext field and the ThreadBarrier extension method:

this._synchronizationContext.Post(OnTemperatureChanged, new WeatherEventArgs(Rand(30f)));

this._synchronizationContext.Post(OnWindChanged, new WeatherEventArgs(Rand(15f)));

this._synchronizationContext.Post(OnHumidityChanged, new WeatherEventArgs(Rand(100f)));

ThreadBarrier Technique #3: Deriving from a ThreadBarrier

Again if the developer is in full control of the worker class, all that it takes is deriving from a ThreadBarrier to inherit the method that provides the posting to the UI thread:

public class WeatherChecker : ThreadBarrier

Raising the events is now a matter of calling the Post method in the base ThreadBarrier class:

Post(OnTemperatureChanged, new WeatherEventArgs(Rand(30f)));

Post(OnWindChanged, new WeatherEventArgs(Rand(15f)));

Post(OnHumidityChanged, new WeatherEventArgs(Rand(100f)));

In order for the ThreadBarrier to work the WeatherChecker class needs to be created on the UI thread so the base ThreadBarrier class can capture the UI’s SynchronizationContext.

ThreadBarrier Technique #4: Creating an instance of a ThreadBarrier

If deriving from a ThreadBarrier is not an option, just creating an instance of a ThreadBarrier will work as well. This implementation is similar to the extension method sample, but the ThreadBarrier instance will hide the capturing and storing of the SynchronizationContext. This technique also requires the WeatherChecker to be created on the UI thread.

private ThreadBarrier _threadBarrier;

 

public WeatherChecker()

{

this._threadBarrier = new ThreadBarrier();

}

this._threadBarrier.Post(OnTemperatureChanged, new WeatherEventArgs(Rand(30f)));

this._threadBarrier.Post(OnWindChanged, new WeatherEventArgs(Rand(15f)));

this._threadBarrier.Post(OnHumidityChanged, new WeatherEventArgs(Rand(100f)));

ThreadBarrier Technique #5: Creating an adapter class to propagate events

This technique should be a last resort for the scenario where you can’t derive from the worker class and you are unable to modify its code. Since an extra set of events need to be created and subscribed, it can be dangerous and lead to memory leaks if the handlers are not properly removed.

Adapter Class (extra events removed for compactness)

public class ThreadBarrierWeatherChecker : ThreadBarrier

{

public event EventHandler<WeatherEventArgs> TemperatureChanged;

 

private WeatherChecker _weatherChecker;

 

public ThreadBarrierWeatherChecker()

{

}

 

public void Attach(WeatherChecker weatherChecker)

{

this._weatherChecker = weatherChecker;

this._weatherChecker.TemperatureChanged += new EventHandler<WeatherEventArgs>(_weatherChecker_TemperatureChanged);

}

 

public void Detach()

{

this._weatherChecker.TemperatureChanged -= new EventHandler<WeatherEventArgs>(_weatherChecker_TemperatureChanged);

this._weatherChecker = null;

}

 

void _weatherChecker_TemperatureChanged(object sender, WeatherEventArgs e)

{

Post(OnTemperatureChanged, e);

}

 

protected virtual void OnTemperatureChanged(WeatherEventArgs e)

{

if (this.TemperatureChanged != null)

{

this.TemperatureChanged(this, e);

}

}

}

The adapter class needs to provide a way to attach and detach to an already existing WeatherChecker instance. If the instance is not detached, it will result in a memory leak (the adapter class will be kept alive).

The Original ThreadBarrier Implementation Flaw

The first implementation of the ThreadBarrier used the event as a parameter:

protected void PostEvent<T>(EventHandler<T> eventHandler, object sender, T eventArgs)

where T : EventArgs

{

//do not raise the event if none was provided

if (eventHandler == null)

{

return;

}

 

this._synchronizationContext.Post(delegate { eventHandler(this, eventArgs); }, null);

}

The problem with this implementation is that the event handler delegate is copied when passed to the method. During execution of this method (which occurs on the worker thread) a UI thread could remove the original handler and dispose of the UI control. Since the method’s copy of the delegate will still get posted to the UI thread, the handler will be executed in the control’s code even though the control was already disposed. In other words, if the worker class is being used by multiple windows or controls that are opening and closing it could lead to this problem. See Problem #2 in the Events and Threads post.

ThreadBarrier FAQ

Q: Why not just use AsynchOperationManager.SynchronizationContext in the base class for each method post?
A: Since the methods are originally called on the worker thread, it means the call to the AsynchOperationManager.SynchronizationContext static property will be made from the worker thread. It will thus return an ‘empty’ SynchronizationContext. The call to the static property must be made on the UI and the SynchronizationContext must be ’saved’ so the worker can use it.

Q: Why not just use SynchronizationContext.Current?
A: The static SynchronizationContext.Current returns null when called from a worker thread, while AsynchOperationManager.SynchronizationContext will at least return an empty SynchronizationContext so we at least have some context reference.

Q: What is the difference between a ThreadBarrier and BackgroundWorker?
A: The BackgroundWorker must also be created on a UI thread. However, the BackgroundWorker does not provide an easy and transparent way (other than ReportProgress) to post events and data from the worker to the UI thread. A ThreadBarrier will support any kind of event since it uses generics.

Q: Why not use WPF’s built in cross-thread binding support?
A: A ThreadBarrier can be used in combination with WPF’s cross-thread binding. The difference is that a ThreadBarrier (and events) allow arbitrary code in the UI to execute. Properties just represent data.

Download the examples.

kick it on DotNetKicks.com

Events and Threads

Tuesday, July 22nd, 2008

EDIT (12/6/2014): If you like C#, WPF, 3D, and Golf, check out my latest side project: https://www.youtube.com/watch?v=8pWq8vhZqbg
If you don’t like golf, don’t click the link!

The purpose of this post is to provide not only a reference for events and multithreading, but also as a background for the fix to the ThreadBarrier pattern I previously introduced. The original ThreadBarrier implementation has a flaw (Problem #2 below). Rather than just posting the fix and not describing the problem in detail, I think it is better to provide an analysis and thorough investigation into the bug so that we all can learn together about the subtleties involved in multithreading. Remember: multithreading is hard. Tomorrow I will revisit the ThreadBarrier pattern with the fix as well as new ideas on how to use it. Until then, the following post shows several solutions to various problems with events and multithreading. I can’t take credit for all of it; most of it has been covered already here, here, and here.

Problem #1: Race condition while raising event

As long as your class is not intended to be thread-safe, it is best to implement events using the following well known pattern:

private event EventHandler MyEvent;

 

protected virtual void OnMyEvent(EventArgs e)

{

if (MyEvent != null)

{

MyEvent(this, e);

}

}

However, this pattern is not safe for use in multithreaded scenarios. The reason is because between the check for null and the calling of the handler, code executing on another thread may remove the handler. The check for null will pass, but when the call to the handler is made, it may then be null which causes a NullReferenceException. To illustrate how this can happen, consider the following code execution example.

UI Thread Worker Thread

protected virtual void OnMyEvent(EventArgs e)

{

if (MyEvent != null)

{

MyEvent -= new EventHandler(MyClass_MyEvent);

MyEvent(this, e);

}

}

Solution 1.A

One solution is to make a copy of the event delegate before performing the check for null:

protected virtual void OnMyEvent(EventArgs e)

{

EventHandler eventHandler = this.MyEvent;

if (eventHandler != null)

{

eventHandler(this, e);

}

}

Since delegates are immutable, when the same UI/Worker code execution sequence occurs, the eventHandler copy will never be affected no matter how or when handlers are added or removed from MyEvent:

UI Thread Worker Thread

protected virtual void OnMyEvent(EventArgs e)

{

EventHandler eventHandler = this.MyEvent;

if (eventHandler != null)

{

MyEvent -= new EventHandler(MyClass_MyEvent);

//eventHandler will never change even

//if handlers are removed to added to MyEvent

eventHandler(this, e);

}

}

Solution 1.B

According to various blog posts, there is a potential problem with solution 1.A. According to this post, Juval Lowy claims JIT compiler inlining may eliminate the copy and bring us back to the original problem. The solution is to raise the event in another method and use the attribute MethodImplOptions.NoInlining. Since passing the event to the method effectively makes a copy for us, we do not need to make another copy in the method.

protected virtual void OnMyEvent(EventArgs e)

{

RaiseEvent(this.MyEvent, e);

}

protected virtual void OnMyGenericEvent(MyEventArgs e)

{

RaiseEvent<MyEventArgs>(this.MyGenericEvent, e);

}

 

[MethodImpl(MethodImplOptions.NoInlining)]

private void RaiseEvent(EventHandler eventHandler, EventArgs e)

{

if (eventHandler != null)

{

eventHandler(this, e);

}

}

 

[MethodImpl(MethodImplOptions.NoInlining)]

private void RaiseEvent<T>(EventHandler<T> eventHandler, T e)

where T : EventArgs

{

if (eventHandler != null)

{

eventHandler(this, e);

}

}

If we are using .NET 3.5 or higher we can create a single extension method to do all of this work for us:

public static class EventExtensions

{

[MethodImpl(MethodImplOptions.NoInlining)]

public static void RaiseEvent(this EventHandler eventHandler, object sender, EventArgs e)

{

if (eventHandler != null)

{

eventHandler(sender, e);

}

}

 

[MethodImpl(MethodImplOptions.NoInlining)]

public static void RaiseEvent<T>(this EventHandler<T> eventHandler, object sender, T e)

where T : EventArgs

{

if (eventHandler != null)

{

eventHandler(sender, e);

}

}

}

Now raising events becomes very easy:

private event EventHandler MyEvent;

private event EventHandler<MyEventArgs> MyGenericEvent;

 

protected virtual void OnMyEvent(EventArgs e)

{

this.MyEvent.RaiseEvent(this, e);

}

protected virtual void OnMyGenericEvent(MyEventArgs e)

{

this.MyGenericEvent.RaiseEvent<MyEventArgs>(this, e);

}

Problem #2: Raising an event causes handler to execute in a disposed object

Now we are getting into the subtle areas of multithreading. This is an important scenario to understand because even though it may seem unlikely, it is actually quite easy to get bitten by this bug. To keep things simple, we will use the 1.A solution for the demonstration. The problem can occur when a listener on the UI thread removes its handler and is disposed, all before the worker thread calls the handler copy. This problem is not limited to a worker/UI thread scenario, it exists for any scenario where multiple threads are adding or removing event handlers.

SideNote: Event handlers are always executed on the thread that raised them, not the thread that added or removed the handler. For example, A UI control could start 10 worker threads where each worker adds an event handler. If the UI thread raises the event, all 10 handlers will execute on the UI thread.

To demonstrate problem #2, consider the following user control:

public partial class MyUserControl : UserControl

{

public event EventHandler MyEvent;

 

public MyUserControl()

{

InitializeComponent();

}

 

public void DemonstrateEventRaisedWhenDisposed()

{

this.MyEvent += new EventHandler(MyUserControl_MyEvent);

new Thread(() => OnMyEvent(EventArgs.Empty)).Start();

this.MyEvent -= new EventHandler(MyUserControl_MyEvent);

Dispose();

}

 

void MyUserControl_MyEvent(object sender, EventArgs e)

{

//do something with the UI here

}

 

protected virtual void OnMyEvent(EventArgs e)

{

EventHandler eventHandler = this.MyEvent;

if (eventHandler != null)

{

eventHandler(this, e);

}

}

}

If you are not familiar with lambda expressions, basically what is happening is that when DemonstrateEventRaisedWhenDisposed is called:

  1. An event handler is added to MyEvent
  2. A thread is started that will call OnMyEvent which raises MyEvent
  3. The previously added event handler from MyEvent is removed
  4. The control is disposed

Since there is no guarantee when the thread will start and execute, the code could execute in a safe way such as:

UI Thread Worker Thread

public void DemonstrateEventRaisedWhenDisposed()

{

this.MyEvent += new EventHandler(MyUserControl_MyEvent);

this.MyEvent -= new EventHandler(MyUserControl_MyEvent);

protected virtual void OnMyEvent(EventArgs e)

{

EventHandler eventHandler = this.MyEvent;

if (eventHandler != null)

{

eventHandler(this, e);

}

}

Dispose();

}

In this scenario, the event will not be raised by the worker thread, therefore the control will safely dispose and nothing bad will happen. But all it takes is some bad timing and a few context switches by the OS to expose the problem:

UI Thread Worker Thread

public void DemonstrateEventRaisedWhenDisposed()

{

this.MyEvent += new EventHandler(MyUserControl_MyEvent);

protected virtual void OnMyEvent(EventArgs e)

{

EventHandler eventHandler = this.MyEvent;

if (eventHandler != null)

{

this.MyEvent -= new EventHandler(MyUserControl_MyEvent);

Dispose();

}

eventHandler(this, e);

void MyUserControl_MyEvent(object sender, EventArgs e)

{

//two bad things: control is disposed, and we are

//executing on a worker thread in the control’s code

}

All it took was the worker to pass the null check with the delegate copy, the UI thread removing the original handler then disposing, and then the worker calling the handler that was never removed from the copy. The MyUserControl_MyEvent method will effectively be executing in the UI control code (yet still on the worker thread; a post to the UI thread is needed to update the UI) even though the control has been disposed.

Solution 2.A

Unfortunately if we do not put any restrictions on which thread handles the events, there is little we can do to solve the problem. But if we constrain our requirements such that events must only be handled on the UI thread, we are able to come up with a relatively simple solution. The solution is to always call the OnXXX method on the UI thread. If a worker needs to raise the event, the worker should post the OnXXX method to the UI thread. This will guarantee that the handlers will never be called when null. This requirement also allows us to remove the need for the copy since we specified that worker threads will not be listening for the event. Using an extension method and the UI’s SynchronizationContext (for posting to the UI thread) gives the simple solution:

public static void PostExt<T>(this SynchronizationContext synchronizationContext, T eventArgs, SendOrPostCallback func)

{

synchronizationContext.Post(func, eventArgs);

}

A call from a worker thread would use the UI’s synchronization context to post the OnXXXmethod to the UI thread for safely raising the event:

synchronizationContext.PostExt(EventArgs.Empty, e => OnMyEvent(EventArgs.Empty))

The synchronizationContext variable is the SynchronizationContext that was captured on the UI thread before the worker was started. For more information read the original ThreadBarrier article and stay tuned for tomorrow’s complete coverage and solution using this technique.

Solution 2.B

If our requirements are unconstrained and any object on any thread could be listening for events, we are in trouble. The only way to prevent the race condition is to lock around the event’s null check and handler call. However this is bad practice since it can lead to deadlocks (subject for another blog entry).

Do not use this code:

private event EventHandler MyEvent;

private object myEventObject = new object();

 

protected virtual void OnMyEvent(EventArgs e)

{

lock (myEventObject)

{

this.MyEvent.RaiseEvent(this, e);

}

}

Problem #3: Adding and removing of event handlers is not thread-safe by default

When a standard event is declared in a class and no Add/Remove accessors are explicitly defined, the C# 2.0+ compiler automatically make accesses to the event thread-safe. Consider the following standard event:

private event EventHandler MyEvent;

The compiler will automatically create thread-safe accessors:

[MethodImpl(MethodImplOptions.Synchronized)]

private void add_MyEvent(EventHandler value)

{

this.MyEvent = (EventHandler)Delegate.Combine(this.MyEvent, value);

}

[MethodImpl(MethodImplOptions.Synchronized)]

private void remove_MyEvent(EventHandler value)

{

this.MyEvent = (EventHandler)Delegate.Remove(this.MyEvent, value);

}

Unfortunately there is still a problem. When subscribing to the event in the following way:

 

MyEvent += new EventHandler(MyClass_MyEvent);

The compiler will convert this to:

MyEvent = (EventHandler)Delegate.Combine(MyEvent, new EventHandler(MyClass_MyEvent));

This makes the operation not thread-safe. It is almost as if the compiler only went half way to thread safety. If we were to start two threads running in parallel both adding and removing a handler (only one is shown below):

int numLoops = 10000000;

Thread thread1 = new Thread(() => {

for (int i = 0; i < numLoops; ++i)

{

this.MySafeEvent += new EventHandler(EventHandlerMethod);

this.MySafeEvent -= new EventHandler(EventHandlerMethod);

}

});

thread1.IsBackground = true;

thread1.Start();

If the adding and removing of the event were thread-safe, once both threads were complete the event should have zero handlers. Since the operation is not thread-safe, what happens is the event will have a few extra handlers due to races.

Solution 3.A

If multiple threads need to add and remove handlers, the event should be designed using the following pattern:

private object mySafeEventLock = new object();

private EventHandler mySafeEventHandler;

 

public event EventHandler MySafeEvent

{

add

{

lock (this.mySafeEventLock)

{

this.mySafeEventHandler += value;

}

}

remove

{

lock (this.mySafeEventLock)

{

this.mySafeEventHandler -= value;

}

}

}

The C# compiler will now make adding and removing handlers normal. This is code after compilation (identical to before compilation):

MySafeEvent += new EventHandler(this.EventHandlerMethod);

However, the addition and removal of the event is converted (again this is post compilation):

public event EventHandler MySafeEvent

{

add

{

lock (this.mySafeEventLock)

{

this.mySafeEventHandler = (EventHandler)Delegate.Combine(this.mySafeEventHandler, value);

}

}

remove

{

lock (this.mySafeEventLock)

{

this.mySafeEventHandler = (EventHandler)Delegate.Remove(this.mySafeEventHandler, value);

}

}

}

But since the handler update is happening inside the lock, the adds and removes are thread-safe. Click here for a sample that demonstrates both safe and unsafe event designs.

Conclusion

There are many mind bending scenarios involved when events are mixed with multithreading. It is best to try and keep things as simple as possible. Hopefully this post serves as a great reference for things to think about when designing your events, classes, and threads.

kick it on DotNetKicks.com

Stop Polluting the UI Thread – Use a DelegateMarshaler

Tuesday, July 22nd, 2008

EDIT (12/6/2014): If you like C#, WPF, 3D, and Golf, check out my latest side project: https://www.youtube.com/watch?v=8pWq8vhZqbg
If you don’t like golf, don’t click the link!

Introduction

Update – ThreadBarrier was a poorly chosen name, use the latest DelegateMarshaler implementation instead.

With the advent of multi-core processors becoming standard in desktop PCs, it is clear we are on the verge of a shift in which high level software is designed and developed. First there was Object Oriented programming, then design patterns, and now there is multithreading. Multithreading has been around for decades in high end computing, but due to the now wide availability of multiple cores in a standard PC or laptop, it is only now that it is beginning to gain mainstream attention. There is a lot of work to do for tools, frameworks, and patterns to simplify the design and debugging of multithreading programs. While Microsoft has been working diligently to improve their tools (Visual Studio) and frameworks (Task Parallel Library) to bring multithreading into the mainstream, there is not yet enough guidance and information on the internet about proper threading techniques and design patterns.

This is where the ‘ThreadBarrier’ pattern comes in. Ultimately it is a way to help simplify the interaction between the UI and worker threads. A ThreadBarrier is an encapsulation of thread execution inside a class such that it is not exposed to the outside world. Rather, external events are first posted to the UI thread so any listener (on the UI thread) does not have to worry about threading issues. Like any pattern, there are times where it is ideal to use and there are times where it does not apply. Use at your own discretion.

Background

It seems that nearly every introductory threading example on the internet consists of a button click that starts a thread that performs some operation in a worker thread in the UI code behind. While simple examples are good, this immediately introduces a developer to starting threads In UI code and thinking that such techniques are normal.

The Problem

The problem is that the only way most developers know how to get data back to the UI thread is to use a UI control to post back the information. In case you are new to threading: the golden rule is that all UI controls (windows, textboxes, progressbars, etc.) can only be accessed from the thread that created them (the UI thread of course). This means a worker thread cannot do myTextBox.Text=”asdf” otherwise a cross-thread exception will be thrown. Controls provide a mechanism for executing a method on the UI thread (Control.Invoke, Control.BeginInvoke, Dispatcher.Invoke, Dispatcher.BeginInvoke).

WinForms example:

delegate void SetStartDelegate(bool enabled);

 

public void SetStartEnabled(bool enabled)

{

if (this.InvokeRequired == false)

{

this.buttonStart.Enabled = enabled;

}

else

{

this.Invoke(new SetStartDelegate(SetStartEnabled), new object[] { enabled });

}

}

WPF example:

delegate void SetStartDelegate(bool enabled);

 

public void SetStartEnabled(bool enabled)

{

if (this.Dispatcher.CheckAccess() == true)

{

this.buttonStart.IsEnabled = enabled;

}

else

{

this.Dispatcher.Invoke(DispatcherPriority.Send, new SetStartDelegate(SetStartEnabled), enabled);

}

}

There are tricks to make this a bit cleaner, but that is the common way to update the UI from any thread.

The combination of the Control’s UI thread rule and a Control’s ability to invoke on the UI thread essentially handcuffs developers into mixing threads with the UI and trying to make it work. Perhaps some have tried to be smart and hide the threads away deep in non-UI code to keep the UI clean. Those developers probably end up with the following questions (at least I did):

“How the heck do you get a control for invoking that deep in the execution and far away from the UI code? And more importantly, why does it have to be this way? There has to be a better way.”

The Answer

There is a better way, and it involves a SynchronizationContext. Rather than use a Control to post execution back to the UI, a SynchronizationContext provides this same capability without the UI Control requirement. Since a fantastic CodeProject article already covers the SynchronizationContext in depth, a summary will only be described here.

SynchronizationContext Overview

-SynchronizationContext is an abstract base class for:
-WindowsFormsSynchronizationContext
-DispatcherSynchronizationContext
-WinForms automatically creates an instance of WindowsFomsSynchronizationContext for a WinForms UI thread.
-WPF automatically creates an instance of DispatcherSynchronizationContext for a WPF UI thread.
-Static property AsyncOperationManager.SynchronizationContext gets the SynchronizationContext for the calling thread: WindowsFormsSynchronizationContext in WinForms and DispatcherSynchronizationContext in WPF.
-SynchronizationContext provides two methods (Send and Post) for synchronous or asynchronous method invocation.
-Getting AsyncOperationManager.SynchronizationContext on a non-UI thread (such as in a console app or worker thread) returns the base SynchronizationContext class that just invokes a method on the calling thread when Send is used, and calls a method on a ThreadPool thread when Post is used.

Introducing the ThreadBarrier ‘Pattern’

The ThreadBarrier pattern consists of a non-UI class encapsulating and executing a worker thread and always raising its events on the UI thread using a SynchronizationContext. The worker thread execution should never leave the class via events. Data and objects within the class may be operated upon by the worker thread but all external events must be called on the UI thread. If this technique is correctly followed then the listening UI code does not need to worry about thread checks and delegate posting.

Implementing a ThreadBarrier’ (.NET 2.0)

A ThreadBarrier can be implemented as an abstract class so that derived classes automatically inherit the necessary functionality to support the pattern.

public abstract class ThreadBarrier

{

private SynchronizationContext _synchronizationContext;

 

protected ThreadBarrier()

{

this._synchronizationContext = AsyncOperationManager.SynchronizationContext;

}

The SyncronizationContext must be stored as a field so that it can be used by the worker thread in the derived class. Since the static AsyncOperationManager.SynchronizationContext property is called in the constructor, a critical requirement of properly using a ThreadBarrier derived class is that it must be created on the thread in which events want to be raised. In other words, create the class on the UI thread so that the UI’s context is captured. A worker thread can then use this context to post the methods that raise events back to the UI. The following protected method can be used for posting OnXXX methods:

public void Post<T>(Action<T> raiseEventMethod, T e)

where T : EventArgs

{

if (this._synchronizationContext == null)

{

ThreadPool.QueueUserWorkItem(delegate { raiseEventMethod(e); });

}

else

{

this._synchronizationContext.Post(delegate { raiseEventMethod(e); }, null);

}

}

For an event such as:

 

public event EventHandler Stopped;

protected virtual void OnStopped(EventArgs e)

{

if (this.Stopped != null)

{

this.Stopped(this, e);

}

}

A ThreadBarrier derived class simply posts events to the UI in this way:

 

Post(OnStopped, EventArgs.Empty);

A small example of a class implementing a ThreadBarrier would look like:

 

public class WeatherChecker : ThreadBarrier

{

public event EventHandler<WeatherEventArgs> TemperatureChanged;

public event EventHandler<WeatherEventArgs> HumidityChanged;

public event EventHandler<WeatherEventArgs> WindChanged;

public event EventHandler Stopped;

 

private bool _isStopRequested;

private Random _random;

 

public WeatherChecker()

{

this._isStopRequested = false;

 

//used for generating random weather information

this._random = new Random((int)DateTime.Now.Ticks);

}

 

public void Start()

{

Thread thread = new Thread(new ThreadStart(CheckWeather));

thread.IsBackground = true; //prevents thread from keeping app alive when app is closed

thread.Start();

}

 

private void CheckWeather()

{

while (this._isStopRequested == false)

{

Post(OnTemperatureChanged, new WeatherEventArgs(Rand(30f)));

Post(OnWindChanged, new WeatherEventArgs(Rand(15f)));

Post(OnHumidityChanged, new WeatherEventArgs(Rand(100f)));

 

//Updates roughly 4 times per second

Thread.Sleep(250);

}

 

Post(OnStopped, EventArgs.Empty);

}

 

public void RequestStop()

{

this._isStopRequested = true;

}

 

private float Rand(float max)

{

return (float)this._random.NextDouble() * max;

}

 

protected virtual void OnTemperatureChanged(WeatherEventArgs e)

{

if (this.TemperatureChanged != null)

{

this.TemperatureChanged(this, e);

}

}

protected virtual void OnHumidityChanged(WeatherEventArgs e)

{

if (this.HumidityChanged != null)

{

this.HumidityChanged(this, e);

}

}

protected virtual void OnWindChanged(WeatherEventArgs e)

{

if (this.WindChanged != null)

{

this.WindChanged(this, e);

}

}

protected virtual void OnStopped(EventArgs e)

{

if (this.Stopped != null)

{

this.Stopped(this, e);

}

}

}

 

The key points are:
-WeatherChecker derives from ThreadBarrier
-The worker thread is started inside this non-UI WeatherChecker class.
-The WeatherChecker should be created on the UI thread.

Now the UI code is very clean and does not have to worry about threads:

public partial class Form1 : Form

{

private WeatherChecker _weatherChecker;

 

public Form1()

{

InitializeComponent();

}

 

private void buttonStart_Click(object sender, EventArgs e)

{

this.buttonStart.Enabled = false;

this.buttonStop.Enabled = true;

 

this._weatherChecker = new WeatherChecker();

this._weatherChecker.TemperatureChanged += new EventHandler<WeatherEventArgs>(_weatherChecker_TemperatureChanged);

this._weatherChecker.HumidityChanged += new EventHandler<WeatherEventArgs>(_weatherChecker_HumidityChanged);

this._weatherChecker.WindChanged += new EventHandler<WeatherEventArgs>(_weatherChecker_WindChanged);

this._weatherChecker.Stopped += new EventHandler(_weatherChecker_Stopped);

 

this._weatherChecker.Start();

}

 

private void buttonStop_Click(object sender, EventArgs e)

{

this._weatherChecker.RequestStop();

}

 

void _weatherChecker_TemperatureChanged(object sender, WeatherEventArgs e)

{

this.labelTemperature.Text = String.Format(“{0:F1} C”, e.Value);

}

 

void _weatherChecker_HumidityChanged(object sender, WeatherEventArgs e)

{

this.labelHumidity.Text = String.Format(“{0:F0}%”, e.Value);

}

 

void _weatherChecker_WindChanged(object sender, WeatherEventArgs e)

{

this.labelWind.Text = String.Format(“{0:F0} mph”, e.Value);

}

 

????????

void _weatherChecker_Stopped(object sender, EventArgs e)

{

this.buttonStop.Enabled = false;

this.buttonStart.Enabled = true;

 

this._weatherChecker = null;

}

}

Implementing a ThreadBarrier (.NET 3.5)

Since the requirement of deriving from a ThreadBarrier class is not ideal, in .NET 3.5 we can use extension methods to help us do the work.

public static class ThreadBarrierExtensions

{

public static void Post<T>(this SynchronizationContext synchronizationContext, Action<T> raiseEventMethod, T eventArgs)

where T : EventArgs

{

if (synchronizationContext == null)

{

ThreadPool.QueueUserWorkItem((e) => raiseEventMethod((T)e), eventArgs);

}

else

{

synchronizationContext.Post((e) => raiseEventMethod((T)e), eventArgs);

}

}

}

 

Now the WeatherChecker class does not have to derive from a ThreadBarrier (but it now has to do the work in its constructor of saving a reference to the SynchronizationContext, the task previously left for the abstract ThreadBarrier class).:

 

public class WeatherChecker

{

private SynchronizationContext _synchronizationContext;

 

public WeatherChecker()

{

this._synchronizationContext = AsyncOperationManager.SynchronizationContext;

}

Using an extension method on the SynchronizationContext allows us to post the OnXXX method:

this._synchronizationContext.Post(OnTemperatureChanged, new WeatherEventArgs(Rand(30f)));

 

Using Lambda expressions also simplifies the handling of the events in the UI code:

 

this._weatherChecker.TemperatureChanged += (weatherChecker, weatherEventArgs) =>

{

this.labelTemperature.Content = String.Format(“{0:F1} C”, weatherEventArgs.Value);

};

Conclusion

The ThreadBarrier technique is an easy way to simplify the use of a worker thread and how it interacts with the UI. It is not the silver bullet for multithreading, but it does offer a way to think of a thread as an ‘object’ and hide the threading complexities. The UI and worker thread can be separated even further by designing a ThreadBarrier class to do nothing but handle events from other threading code (such as in a library that you do not have the code) and propagate just these events to the UI. This truly allows the business ‘logic’ to be free of any UI dependencies.

Samples

  • ThreadBarrier Technique #1: Subclassing an existing worker thread class
  • ThreadBarrier Technique #2: Using extension methods on a SynchronizationContext
  • ThreadBarrier Technique #3: Deriving from a ThreadBarrier
  • ThreadBarrier Technique #4: Creating an instance of a ThreadBarrier
  • ThreadBarrier Technique #5: Creating an adapter class to propagate events
  • Download all Samples

    UPDATE: The DelegateMarshaler has been revisited with a description of the 5 techniques in the sample.

    kick it on DotNetKicks.com