Dispatcher BeginInvoke Syntax

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.

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

Thanks in advance for any enlightenment!

Answers


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);
}

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)));
}

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

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

Need Your Help

Using Chutzpah with VS2012 to run JS tests in an HTML page

javascript visual-studio-2012 chutzpah

I am attempting to run existing qUnit test in Visual Studio 2012 using Chutzpah that are currently in a HTML page and I'm not able to get the VS IDE to recognize the tests. When running a straight JS

PHP-jQuery - How to populate dropdown with month name and set value to month number

javascript php jquery html

I'm trying to populate a dropdown list with month names, another one with days and another one with years and everything is fine except that I'm having issues setting the to be the month number in...