Converting Action method call to async Action method call

后端 未结 2 1929
鱼传尺愫
鱼传尺愫 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 or Func>. An Action is equivalent into a void Action() named method. You can't await on void, yet you can await Task Func() or Task Func:

    public async Task ExecuteAsync(Func 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.

提交回复
热议问题