Question

Usually we invoke on UI thread that way :

myControl.Invoke((MethodInvoker)delegate() { Foo(); });

Are they any way to do it without any control instance ? I mean something like this :

System.Windows.Forms.Thread.Invoke(...);


Solution Solution given by dcastro, using WindowsFormsSynchronizationContext. Here is a really simple example in a form :

public partial class FrmFoo : Form
{
    SynchronizationContext uiThread;

    public void FrmFoo()
    {
        // Needs to assign it from somewhere in the UI thread (in constructor for example)
        uiThread = WindowsFormsSynchronizationContext.Current;
    }

    void AsyncBar()
    {
        uiThread.Send(delegate(object state)
        {
            // UI Cross-Thread dangerous manips allowed here
        }, null);
    }
}
Was it helpful?

Solution

You can use the current WindowsFormsSynchronizationContext (available since .NET 2.0)

System.Threading.SynchronizationContext.Current.Post(delegate, state);

You should grab a reference to the context from your UI thread, and make it accessible to your other threads, which can then use it to execute code on the UI thread.

This is equivalent to BeginInvoke. For a Invoke equivalent, use the Send method instead.

OTHER TIPS

Use SynchronizationContext and it's Post method

var sCon=SynchronizationContext.Current;
        sCon.Post(new SendOrPostCallback((o) => {
            //do your stuffs
        }), null);

SynchronizationContext is just an abstraction, one that represents a particular environment you want to do some work in. As an example of such an environment, Windows Forms apps have a UI thread (while it’s possible for there to be multiple, for the purposes of this discussion it doesn’t matter), which is where any work that needs to use UI controls needs to happen. For cases where you’re running code on a ThreadPool thread and you need to marshal work back to the UI so that this work can muck with UI controls, Windows Forms provides the Control.BeginInvoke method. You give a delegate to a Control’s BeginInvoke method, and that delegate will be invoked back on the thread with which that control is associated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top