Converting Action method call to async Action method call

后端 未结 2 1933
鱼传尺愫
鱼传尺愫 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: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.

提交回复
热议问题