Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert lambda expression to type 'Delegate' because it is not a delegate type

I am having trouble with an anonymous delegate lambda in C#. I just converted the app to C#5 and the delegates went all haywire on me. Any help would be great. The specific error is:

Cannot convert lambda expression to type 'Delegate' because it is not a delegate type

public void UpdateUserList()
{
  if (!Monitor.TryEnter((object)this.LvPerson, 150))
      return;

  if (this.InvokeRequired)
  {
      this.Invoke((Delegate) (() => this.UpdateUserList()));              
  }
  else
  { ... }
}

I have also tried

this.Invoke(() => {this.UpdateUserList();});

I'm not sure where the issue is as this was working before I moved the project from Visual Studio 2008 to Visual Studio 2015.

Thanks again for the help!

like image 849
Jason Coffman Avatar asked Aug 08 '15 22:08

Jason Coffman


1 Answers

The Invoke method expects a Delegate type instance, because you use a lambda expression it cannot automatically translate the expression into something like new Delegate() because Delegate has no public constructors. Using

this.Invoke(new Action(() => {this.UpdateUserList();}));

Should solve the problem as Action is a subclass of Delegate. To get rid of the redundant new Action(...) when using Invoke you can write a set of extension methods that take as argument an Action, this way the new Action(...) will be handled by the C# compiler so you won't have to write it every time making your code cleaner.

In case you are using Invoke for some asynchronous operations that may involve other threads look into Task Parallel Library (TPL) and Task-based Asynchronous Pattern (TAP), the latter has built in support into C# and Visual Basic.NET, using await will no longer require a call to Invoke() and allow you to run some operations on the background freeing your UI.

like image 195
Andrei15193 Avatar answered Oct 19 '22 06:10

Andrei15193