Invoking WPF Dispatcher with anonymous method

前端 未结 4 1381
北海茫月
北海茫月 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);
    

提交回复
热议问题