Converting Action method call to async Action method call

后端 未结 2 1930
鱼传尺愫
鱼传尺愫 2021-02-11 18:15

I\'ve this method

public void Execute(Action action)
{
    try
    {
        action();
    }
    finally
    {
    }
}

and I need to convert it

相关标签:
2条回答
  • 2021-02-11 18:37

    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.

    0 讨论(0)
  • 2021-02-11 18:48

    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.

    0 讨论(0)
提交回复
热议问题