Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type

后端 未结 2 995
野的像风
野的像风 2021-02-14 02:55

I want to execute this code on main thread in WPF app and getting error I can\'t figure out what is wrong:

private void AddLog(string logItem)
        {

                


        
相关标签:
2条回答
  • 2021-02-14 03:39

    Anonymous functions (lambda expressions and anonymous methods) have to be converted to a specific delegate type, whereas Dispatcher.BeginInvoke just takes Delegate. There are two options for this...

    1. Still use the existing BeginInvoke call, but specify the delegate type. There are various approaches here, but I generally extract the anonymous function to a previous statement:

      Action action = delegate() { 
           this.Log.Add(...);
      };
      Dispatcher.BeginInvoke(action);
      
    2. Write an extension method on Dispatcher which takes Action instead of Delegate:

      public static void BeginInvokeAction(this Dispatcher dispatcher,
                                           Action action) 
      {
          Dispatcher.BeginInvoke(action);
      }
      

      Then you can call the extension method with the implicit conversion

      this.Dispatcher.BeginInvokeAction(
              delegate()
              {
                  this.Log.Add(...);
              });
      

    I'd also encourage you to use lambda expressions instead of anonymous methods, in general:

    Dispatcher.BeginInvokeAction(() => this.Log.Add(...));
    

    EDIT: As noted in comments, Dispatcher.BeginInvoke gained an overload in .NET 4.5 which takes an Action directly, so you don't need the extension method in that case.

    0 讨论(0)
  • 2021-02-14 03:39

    You can also use MethodInvoker for this:

    private void AddLog(string logItem)
            {
                this.Dispatcher.BeginInvoke((MethodInvoker) delegate
                {
                    this.Log.Add(new KeyValuePair<string, string>(DateTime.Now.ToLongTimeString(), logItem));
                });
            }
    
    0 讨论(0)
提交回复
热议问题