Dispatcher BeginInvoke Syntax

C#.NetMultithreadingWcf Data-Services

C# Problem Overview


I have been trying to follow some WCF Data Services examples and have the following code:

private void OnSaveCompleted(IAsyncResult result)
    {
        Dispatcher.BeginInvoke(() =>
        {
            context.EndSaveChanges(result);
        });
    }

Which is called by the following:

this.context.BeginSaveChanges(SaveChangesOptions.Batch, this.OnSaveCompleted, null);

Now I am getting a little confused here. Firstly, the first bit of code is showing a syntax error of

> Argument type lambda expression is not assignable to parameter type System.Delegate

So instead of blindly trying to follow the example code, I tried to understand what was going on here. Unfortunately, I am struggling to understand the error plus what is actually happening. Can anyone explain?

I feel a bit stupid as I am sure this is easy.

C# Solutions


Solution 1 - C#

The problem is that the compiler doesn't know what kind of delegate you're trying to convert the lambda expression to. You can fix that either with a cast, or a separate variable:

private void OnSaveCompleted(IAsyncResult result)
{        
    Dispatcher.BeginInvoke((Action) (() =>
    {
        context.EndSaveChanges(result);
    }));
}

or

private void OnSaveCompleted(IAsyncResult result)
{
    Action action = () =>
    {
        context.EndSaveChanges(result);
    };
    Dispatcher.BeginInvoke(action);
}

Solution 2 - C#

Answer by Jon Skeet is very good but there are other possibilities. I prefer "begin invoke new action" which is easy to read and to remember for me.

private void OnSaveCompleted(IAsyncResult result)
{       
    Dispatcher.BeginInvoke(new Action(() =>
    {
        context.EndSaveChanges(result);
    }));
}

or

private void OnSaveCompleted(IAsyncResult result)
{       
    Dispatcher.BeginInvoke(new Action(delegate
    {
        context.EndSaveChanges(result);
    }));
}

or

private void OnSaveCompleted(IAsyncResult result)
{       
    Dispatcher.BeginInvoke(new Action(() => context.EndSaveChanges(result)));
}

Solution 3 - C#

If your method does not require parameters, this is the shortest version I've found

Application.Current.Dispatcher.BeginInvoke((Action)MethodName); 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJon ArchwayView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#CoperNickView Answer on Stackoverflow
Solution 3 - C#Alon AmsalemView Answer on Stackoverflow