Invoking WPF Dispatcher with anonymous method

前端 未结 4 1365
北海茫月
北海茫月 2021-01-17 22:38

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

Dispatcher.Invoke(DispatcherPriority.Normal, delegate()
{
           


        
相关标签:
4条回答
  • 2021-01-17 23:08

    Look at the signature for Dispatcher.Invoke(). It doesn't take Action or some other specific delegate type. It takes Delegate, which is the common ancestor of all delegate types. But you can't convert anonymous method to this base type directly, you can convert it only to some specific delegate type. (The same applies to lambdas and method groups.)

    Why does it take Delegate? Because you can pass to it delegates that take parameters or have return values.

    The cleanest way is probably:

    Action action = delegate()
    {
        // do stuff to UI
    };
    
    Dispatcher.Invoke(DispatcherPriority.Normal, action);
    
    0 讨论(0)
  • 2021-01-17 23:11

    The 'Delegate' class is abstract so you have to provide the compiler with a type that is derived from it. Any class derived from Delegate will do but Action is usually the most appropriate one.

    0 讨论(0)
  • 2021-01-17 23:18

    I use this one:

    Dispatcher.Invoke((Action)(() => YourCodeHere()));

    0 讨论(0)
  • 2021-01-17 23:22

    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 */ });
    
    0 讨论(0)
提交回复
热议问题