Click here to Skip to main content
13,344,765 members (60,664 online)
Click here to Skip to main content
Add your own
alternative version


121 bookmarked
Posted 3 Oct 2005

Another way to Invoke UI from a Worker Thread

, 3 Oct 2005
Rate this:
Please Sign up or sign in to vote.
This article demonstrates an alternative way of invoking UI event handlers from a worker thread.


This article demonstrates an alternative way of invoking UI event handlers from a worker thread.

Events from worker threads - the "traditional" way

One of the benefits of the .NET platform is a much simpler way of performing lengthy tasks while keeping the user interface responsive. You can create an object, fill its properties and fields with proper data and make one of the object's methods a background thread. And just don't forget to retrieve the result of its work some time later.

When a background also known as worker thread needs to display some information in a UI you just define an event, subscribe a UI object for this event and fire it in the background thread. The only problem is that the UI should be managed from its own thread that contains the message loop. Microsoft offers us a simple workaround.

Suppose we have an event handler like the following one:

void OnEvent(object sender, EventArgs e)
    // Update the UI

It would work for any object derived from System.Windows.Forms.Control. To make it thread-safe, you should add a little bit of code:

void OnEvent(object sender, EventArgs e)
        Invoke(new EventHandler(OnEvent), 
                    new object[] {sender, e});
        // Update the UI

The InvokeRequired property of the Control class returns true if the method of the UI element is called from a different thread. In this case we should use interthread marshalling using the Invoke method.

The "traditional" way of making multithreaded Windows Forms programs is good, but imagine you have a rather chatty worker object that has a lot of events. So for each event you should modify your event handlers. I usually forget to do this and then hunt for bugs. I also think this workaround code is ugly and should be hidden from the worker's client. We should move it to the workers' methods and I'll show you how to do that.

Events from worker threads, an easier way

Microsoft uses a distinct pattern for raising events. Each event with the name AAA is accompanied with a protected method OnAAA that raises the event and can be overridden by the descendant classes. There are many reasons to use this pattern in your programs and I'm going to give you another one. Checking whether we are calling the UI from a non-UI thread should be performed in such a method.

You would ask how? Easy. The Control class actually implements System.ComponwentModel.ISynchronizeInvoke interface. This interface declares the property InvokeRequired and methods Invoke, BeginInvoke and EndInvoke so, in theory there are more message loop aware classes. While firing events we need to check if each target object implements this interface. If it does, we need to check the InvokeRequired property and instead of calling the event delegate directly we need to use the Invoke method. It means that for the event subscriber (a Form-derived class in most cases) this event will always be synchronous and the author of the subscriber won't need to bother about interthread marshalling.

However, we should keep in mind that all events are multicast delegates. Because of this we must check all event subscriber objects separately. This is an easy part, because System.MulticastDelegate class has the GetInvocationList method that returns an array of single cast delegates that represent the combined multicast delegate.

Suppose we have an event declared as:

public event EventHandler Event;

We should declare the accompanying method like this:

protected virtual void OnEvent(EventArgs e)
    EventHandler handler = Event;
    if(null != handler)
        foreach(EventHandler singleCast in handler.GetInvocationList())
            ISynchronizeInvoke syncInvoke = 
                       singleCast.Target as ISynchronizeInvoke;
                if((null != syncInvoke) && (syncInvoke.InvokeRequired))
                                  new object[] {this, e});
                    singleCast(this, e);

The first line of the method, the assignment statement, makes the method thread safe. I get a local copy of the event handler and make sure that even if somebody modifies the Event there won't be any trouble. Then we check if there is any subscriber for the event. If there are subscribers, I check if the event's delegate target object implements the ISynchronizeInvoke interface. If it does and the object is in the UI thread I perform interthread marshalling. In all other cases I just call the delegate directly. I also catch all exceptions that a subscriber can throw. It is not a very good idea to ignore them but so far I haven't found a good way to pass them to the OnAAA method caller.


In the sample you'll find a simple component named Copier that copies one stream to another in the background thread. You might need a class like that if you copy big files or download data from Internet. The Copier class has some properties related to work progress, three thread-safe events Started, Progress and Finished and three public methods Start, Stop and Join that check the state of the Copier and if it is valid delegates the work to the System.Threading.Thread method.

The sample also contains the ProgressForm class that provides a simple UI for the Copier component and the MainForm class that allows the user to specify the names of the source and target files. Note that the Copier does not close the data streams; this is the responsibility of the Copier's client. The same is true for the ProgressForm class.

There are two points of interest in this code. First is the implementation of the OnStarted, OnProgress and OnFinished methods, they follow the described pattern. Second is the ability to cancel the worker thread. Initially, I derived ProgressEventArgs class from CancelEventArgs, but the Control.Invoke call does not marshal its arguments back to the calling thread. I've added the Stop call to the Copier class that gracefully stops the worker thread.

I wrote the sample using SharpDevelop IDE with NAnt 0.85 as the build system. With NAnt you should call Debug, Release or Doc targets; the latter creates the InvokeUI.chm HTML Help file in the doc folder. You can also use the build.bat file to compile the sample. Sorry, I have no Visual Studio and those of you who do will have to re-create the project. Just create an empty Windows Forms project and add all *.cs files to it.


Files Copier.cs, ProfressEvent.cs and ProgressForm.cs are covered by BSD-like license, see comments at the beginning of each file. The rest of the code is in public domain. Use the sample at your own risk.


  • Here you can learn about SharpDevelop and download your copy.
  • Here you can learn about NAnt and download your copy. Personally, I recommend this tool.
  • MSDN article: "Defining an Event" - describes the Event/OnEvent pattern and shows how to optimize the event implementation by using System.ComponentModel.EventHandlerList class.
  • Articles by Chris Sells: "Safe, Simple Multithreading in Windows Forms" - simple and clear explanation on how multithreaded UI works in Windows Forms.
  • A blog entry by Patrick Cauldwell that describes a problem with InvokeRequired property.

Revision history

  • 03/09/05
    • Initial post.
  • 04/09/05
    • Fixed a serious bug with background thread canceling; fixed a ProgressForm label issue; HtmlHelp compilation added to the build file.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Alexey A. Popov
Web Developer
Russian Federation Russian Federation
I'm a system administrator from Moscow, Russia. Programming is one of my hobbies. I presume I'm one of the first Russians who created a Web site dedicated to .Net known that time as NGWS. However, the Web page has been abandoned a long ago.

You may also be interested in...


Comments and Discussions

QuestionCreated an Extension for this. Pin
Gary J Mason23-Feb-15 4:18
memberGary J Mason23-Feb-15 4:18 
GeneralGeneric version Pin
jsoldi22-Dec-10 10:59
memberjsoldi22-Dec-10 10:59 
GeneralQuestion Pin
SDI200330-Oct-07 17:12
memberSDI200330-Oct-07 17:12 
I took the conversion mod in the blog -- modified it a bit for use in a rs232 com dll for use with a asyncronous pressure guage. It works great with a form but I am also using this in a windows service. It errors out trying to directcast unless I put "implements isynchronizeinvoke" in the service class. but that adds the four required sub routines which I don't really want -- is there another way to make it work without using the implements isynchronizeinvoke in the service class?

My basic structure

Service class ITR90Service
implements isynchronizeinvoke

private withevents itr90comm as itr90_rs232_comwrapper

private sub PressureEvent(sender as....handles itr90com.PressureChange

'''follwing 4 routines added and needed by the implements

Public Function BeginInvoke(ByVal method As System.Delegate, ByVal args() As Object) As System.IAsyncResult Implements System.ComponentModel.ISynchronizeInvoke.BeginInvoke

End Function

Public Function EndInvoke(ByVal result As System.IAsyncResult) As Object Implements System.ComponentModel.ISynchronizeInvoke.EndInvoke

End Function

Public Function Invoke(ByVal method As System.Delegate, ByVal args() As Object) As Object Implements System.ComponentModel.ISynchronizeInvoke.Invoke

End Function

Public ReadOnly Property InvokeRequired() As Boolean Implements System.ComponentModel.ISynchronizeInvoke.InvokeRequired

End Get
End Property

thanks in advance

Steven Infante
GeneralRe: Question --- Found a solution but there must be a better way Pin
SDI200330-Oct-07 19:53
memberSDI200330-Oct-07 19:53 
AnswerRe: Question --- Found a solution but there must be a better way Pin
Alexey A. Popov31-Oct-07 10:56
memberAlexey A. Popov31-Oct-07 10:56 
GeneralRe: Question --- Found a solution but there must be a better way Pin
SDI200331-Oct-07 13:08
memberSDI200331-Oct-07 13:08 
QuestionRe: Question --- Found a solution but there must be a better way Pin
SDI20031-Nov-07 4:14
memberSDI20031-Nov-07 4:14 
AnswerRe: Question --- Found a solution but there must be a better way Pin
Alexey A. Popov1-Nov-07 6:25
memberAlexey A. Popov1-Nov-07 6:25 
GeneralRe: Question --- Found a solution but there must be a better way Pin
SDI20031-Nov-07 14:40
memberSDI20031-Nov-07 14:40 
GeneralRe: Question --- Found a solution but there must be a better way Pin
Alexey A. Popov1-Nov-07 23:53
memberAlexey A. Popov1-Nov-07 23:53 
AnswerRe: Question --- Found a solution but there must be a better way Pin
SDI20032-Nov-07 21:00
memberSDI20032-Nov-07 21:00 
GeneralRe: Question Pin
Paul B.24-Jan-09 10:16
memberPaul B.24-Jan-09 10:16 
GeneralGeneric revisitation Pin
Nikso26-Jul-07 4:55
memberNikso26-Jul-07 4:55 
GeneralRe: Generic revisitation Pin
Alexey A. Popov31-Oct-07 10:52
memberAlexey A. Popov31-Oct-07 10:52 
GeneralRe: Generic revisitation Pin
Shannon McCoy28-Jul-09 1:16
memberShannon McCoy28-Jul-09 1:16 
GeneralRe: Generic revisitation Pin
jsoldi22-Dec-10 11:00
memberjsoldi22-Dec-10 11:00 
QuestionVB.NET Conversion? Pin
NightOwl88824-Jun-07 15:14
memberNightOwl88824-Jun-07 15:14 
AnswerRe: VB.NET Conversion? Pin
Chris Kolkman25-Jun-07 4:26
memberChris Kolkman25-Jun-07 4:26 
GeneralRe: VB.NET Conversion? Pin
Alexey A. Popov25-Jun-07 7:22
memberAlexey A. Popov25-Jun-07 7:22 
GeneralRe: VB.NET Conversion? Pin
Chris Kolkman25-Jun-07 7:31
memberChris Kolkman25-Jun-07 7:31 
AnswerRe: VB.NET Conversion - The Solution [modified] Pin
NightOwl88825-Jun-07 18:38
memberNightOwl88825-Jun-07 18:38 
GeneralRe: VB.NET Conversion - The Solution Pin
Alexey A. Popov26-Jun-07 7:32
memberAlexey A. Popov26-Jun-07 7:32 
AnswerRe: VB.NET Conversion - The Solution Pin
NightOwl88826-Jun-07 15:24
memberNightOwl88826-Jun-07 15:24 
GeneralRe: VB.NET Conversion - The Solution Pin
Alexey A. Popov27-Jun-07 7:29
memberAlexey A. Popov27-Jun-07 7:29 
GeneralRe: VB.NET Conversion? [modified] Pin
Stackohm15-Aug-09 9:39
memberStackohm15-Aug-09 9:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.180111.1 | Last Updated 3 Oct 2005
Article Copyright 2005 by Alexey A. Popov
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid