BeginInvoke(DispatcherPriority, Delegate, Object) Executes the specified delegate asynchronously at the specified priority and with the specified argument on the thread the Dispatcher is associated with.
Invoke(Action, DispatcherPriority) Executes the specified Action synchronously at the specified priority on the thread the Dispatcher is associated with. Invoke(Action) Executes the specified Action synchronously on the thread the Dispatcher is associated with.
You can use Dispatcher even in a WinForms app. If you are sure to be on a UI thread (e.g. in an button. Click handler), Dispatcher. CurrentDispatcher gives you the UI thread dispatcher that you can later use to dispatch from background threads to the UI thread as usual.
BeginInvoke(Action) Executes the specified delegate asynchronously on the thread that the control's underlying handle was created on. BeginInvoke(Delegate) Executes the specified delegate asynchronously on the thread that the control's underlying handle was created on.
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've found
Application.Current.Dispatcher.BeginInvoke((Action)MethodName);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With