Converting Action method call to async Action method call

后端 未结 2 1627
悲&欢浪女
悲&欢浪女 2021-02-11 17:52

I\'ve this method

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

and I need to convert it

2条回答
  •  失恋的感觉
    2021-02-11 18:43

    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.

提交回复
热议问题