Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking WPF Dispatcher with anonymous method

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?

like image 794
djk Avatar asked Jun 05 '11 20:06

djk


1 Answers

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 */ });
like image 53
Jaska Avatar answered Oct 03 '22 06:10

Jaska