I\'ve this method
public void Execute(Action action)
{
try
{
action();
}
finally
{
}
}
and I need to convert it
Try this:
public async void ExecuteAsync(Action action)
{
await Task.Run(action);
}
Using Task.Run()
creates an awaitable by running your action on a different task.
And also bear in mind that handling exceptions on "awaitables" does not work as intended.
Better wrap that action()
call in a try catch an do Task.Run()
on that wrapper.
If you want to await
on a delegate, it has to be of type Func<Task>
or Func<Task<T>>
. An Action
is equivalent into a void Action()
named method. You can't await on void
, yet you can await Task Func()
or Task<T> Func
:
public async Task ExecuteAsync(Func<Task> func)
{
try
{
await func();
}
finally
{
}
}
If this can't be done, it means that internally the method isn't truly asynchronous, and what you actually want to do is execute the synchronous delegate on a thread-pool thread, which is a different matter, and isn't really executing something asynchronously. In that case, wrapping the call with Task.Run
will suffice.