Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type? [duplicate]

Tags:

c#

delegates

wpf

I'm having a problem that I can't seem to figure out, although its kind of a standard question here on Stackoverflow.

I'm trying to update my Bing Maps asynchronously using the following code (mind you, this is from an old Silverlight project and does not seem to work in WPF)

_map.Dispatcher.BeginInvoke(() =>
{
    _map.Children.Clear();
    foreach (var projectedPin in pinsToAdd.Where(pin => PointIsVisibleInMap(pin.ScreenLocation, _map)))
    {
        _map.Children.Add(projectedPin.GetElement(ClusterTemplate));
    }
});

What am I doing wrong?

like image 431
Niels Avatar asked Jan 17 '13 14:01

Niels


3 Answers

You have to cast it explicitly to a Action in order for the conversion to System.Delegate to kick in.

That is:

_map.Dispatcher.BeginInvoke((Action)(() =>
{
    _map.Children.Clear();
    foreach (var projectedPin in pinsToAdd.Where(pin => PointIsVisibleInMap(pin.ScreenLocation, _map)))
    {
        _map.Children.Add(projectedPin.GetElement(ClusterTemplate));
    }
}));
like image 147
Jean Hominal Avatar answered Nov 11 '22 17:11

Jean Hominal


The BeginInvoke() method's parameter is the base Delegate class.

You can only convert a lambda expression to a concrete delegate type.

To fix this issue, you need to explicitly construct a delegate:

BeginInvoke(new MethodInvoker(() => { ... }));
like image 14
SLaks Avatar answered Nov 11 '22 17:11

SLaks


Try

Dispatcher.BeginInvoke(new System.Threading.ThreadStart(delegate
{
//Do something
}));

Or use Action

like image 3
Alex Avatar answered Nov 11 '22 16:11

Alex