Invoking WPF Dispatcher with anonymous method

Hannobo picture Hannobo · Jun 5, 2011 · Viewed 23k times · Source

I just realized in a C# .Net 4.0 WPF background thread that this doesn't work (compiler error):

Dispatcher.Invoke(DispatcherPriority.Normal, delegate()
{
    // do stuff to UI
});

From some examples I found out that it had to be casted like this: (Action)delegate(). However, in other examples it is casted to other classes, e.g. System.Windows.Forms.MethodInvoker.

Can anybody tell me what exactly is wrong with the example above? I also tried to reproduce it with other methods, but it was always working without casting:

delegate void MyAction();
void Method1(MyAction a) {
    // do stuff
}

void Method2(Action a) {
    // do stuff
}

void Tests()
{
    Method1(delegate()
    {
        // works
    });

    Method2(delegate()
    {
        // works
    });

    Method1(() =>
    { 
        // works
    });

    Method2(() =>
    {
        // works
    });

    Method2(new Action(delegate()
    {
        // works
    }));

    new System.Threading.Thread(delegate()
    {
        // works
    }).Start();
}

So whats the best (most elegant, less redundant) way to invoke the Dispatcher, and whats so special with it that delegates must be casted?

Answer

Jaska picture Jaska · Feb 9, 2013

I would like to point out even more cleaner code example to Svick's one, after all we all like one liners don't we?

Dispatcher.Invoke((Action) delegate { /* your method here */ });