将Action方法调用转换为异步Action方法调用 [英] Converting Action method call to async Action method call

查看:80
本文介绍了将Action方法调用转换为异步Action方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种方法

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

我需要将其转换为这样的异步方法调用

and I need to convert it to an async method call like this one

public async Task ExecuteAsync(Action action)
{
    try
    {
        await action();
    }
    finally
    {
    }
}

上面的代码的问题是编译器发出以下错误

The problem with the code above is that the compiler issue the following error

"await"运算符只能在异步lambda中使用表达.考虑使用异步"标记该lambda表达式修饰符.

The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.

推荐答案

如果要对委托进行 await ,则其类型必须为 Func< Task> Func< Task< T>> . Action 等效于名为 void Action()的方法.您无法等待 void ,但是可以等待 Task Func() Task< T>功能:

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
    {
    }
}

如果无法完成,则意味着该方法在内部并不是真正的异步方法,而您真正想做的是在线程池线程上执行同步委托,这是另一回事,并且不是并不是真正地异步执行某些操作.在这种情况下,用 Task.Run 包裹调用就足够了.

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.

这篇关于将Action方法调用转换为异步Action方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆