.net-3.5 - AsyncBridge.Net35.0.2.0,等待任务

标签 .net-3.5 async-await

我正在使用 3.5 版的 asyncbridge,但遇到了问题。 当我有一个返回 void 的方法时,我知道我必须返回一个任务。

但是下面的方法不行

public async Task PingAsync()
{
  return await Task.Factory.FromAsync(client.BeginPing, client.EndPing, new object());
}

当我返回值时,它就像一个魅力,即返回等待Task.FromFactory....

我在这里遗漏了什么吗?

最佳答案

我怀疑你可以将其更改为:

public Task PingAsync()
{
    return Task.Factory.FromAsync(client.BeginPing, client.EndPing, new object());
}

将其设为异步方法没有任何好处 - 您只是尝试创建一个表示异步操作的任务,并且TaskFactory.FromAsync 会为你做到这一点。

如果您确实想要使用asyncawait,只需删除return部分:

public async Task PingAsync()
{
    await Task.Factory.FromAsync(client.BeginPing, client.EndPing, new object());
}

查看 FromAsync 的重载,我怀疑您可能需要 client.BeginPing() 而不是 client.BeginPing...不清楚为什么要创建一个新的对象作为状态,而不是仅仅使用null。想必您没有使用该状态...

关于.net-3.5 - AsyncBridge.Net35.0.2.0,等待任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20946358/

相关文章:

.net-3.5 - .Net 的 AppSettingsReader 与 ConfigurationManager 在读取应用程序配置设置方面的优势

.net - UserPrincipal.FindByIdentity坚持 "There is no such object on the server."

c# - 在 Parallel.ForEach 中嵌套 await

c# - 我可以在 IProgress.Report 上等待吗

javascript - 可以等待然后混合在一个实现中吗?

.net - 如何说服我的管理员从 ASP.NET 2.0 升级到 3.5?

c# - 从磁盘解析大数据文件比在内存中解析慢得多?

wcf - C# WCF REST - 如何使用 JSON.Net 序列化器而不是默认的 DataContractSerializer?

c# - 异常 : The application called an interface that was marshalled for a different thread

python - asyncio.gather() - task.cancelled() 在 task.cancel() 之后为 False