I have a method with some code that does an await
operation:
public async Task DoSomething()
{
var x = await ...;
}
I need that code to run on the Dispatcher thread. Now, Dispatcher.BeginInvoke()
is awaitable, but I can't mark the lambda as async
in order to run the await
from inside it, like this:
public async Task DoSomething()
{
App.Current.Dispatcher.BeginInvoke(async () =>
{
var x = await ...;
}
);
}
On the inner async
, I get the error:
Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type.
How can I work with async
from within Dispatcher.BeginInvoke()
?
The other answer may have introduced an obscure bug. This code:
uses the
Dispatcher.Invoke(Action callback)
override form ofDispatcher.Invoke
, which accepts anasync void
lambda in this particular case. This may lead to quite unexpected behavior, as it usually happens withasync void
methods.You are probably looking for something like this:
In this case,
Dispatch.Invoke<Task<int>>
accepts aFunc<Task<int>>
argument and returns the correspondingTask<int>
which is awaitable. If you don't need to return anything fromDoSomethingWithUIAsync
, simply useTask
instead ofTask<int>
.Alternatively, use one of
Dispatcher.InvokeAsync
methods.Use
Dispatcher.Invoke()