C# Multithreading -- Invoke without a Control C# Multithreading -- Invoke without a Control multithreading multithreading

C# Multithreading -- Invoke without a Control


Look into the AsyncOperation class. You create an instance of AsyncOperation on the thread you want to call the handler on using the AsyncOperationManager.CreateOperation method. The argument I use for Create is usually null, but you can set it to anything. To call a method on that thread, use the AsyncOperation.Post method.


Use SynchronizationContext.Current, which will point to something that you can synchronize with.

This will do the right thing™ depending on the type of application. For a WinForms application, it will run this on the main UI thread.

Specifically, use the SynchronizationContext.Send method, like this:

SynchronizationContext context =    SynchronizationContext.Current ?? new SynchronizationContext();context.Send(s =>    {        // your code here    }, null);


The handling method could simply store the data into a member variable of the class. The only issue with cross-threading occurs when you want to update threads to controls not created in that thread context. So, your generic class could listen to the event, and then invoke the actual control you want to update with a delegate function.

Again, only the UI controls that you want to update need to be invoked to make them thread safe. A while ago I wrote a blog entry on a "Simple Solution to Illegal Cross-thread Calls in C#"

The post goes into more detail, but the crux of a very simple (but limited) approach is by using an anonymous delegate function on the UI control you want to update:

if (label1.InvokeRequired) {  label1.Invoke(    new ThreadStart(delegate {      label1.Text = "some text changed from some thread";    }));} else {  label1.Text = "some text changed from the form's thread";}

I hope this helps. The InvokeRequired is technically optional, but Invoking controls is quite costly, so that check ensure it doesn't update label1.Text through the invoke if its not needed.