c# - 如何编写不带 out 参数的异步方法?

标签 c# async-await

我想写一个带有 out 参数的异步方法,如下所示:

public async void Method1()
{
    int op;
    int result = await GetDataTaskAsync(out op);
}

如何在 GetDataTaskAsync 中执行此操作?

最佳答案

您不能使用带有 refout 参数的异步方法。

Lucian Wischik 解释了为什么在这个 MSDN 线程上这是不可能的:http://social.msdn.microsoft.com/Forums/en-US/d2f48a52-e35a-4948-844d-828a1a6deb74/why-async-methods-cannot-have-ref-or-out-parameters

As for why async methods don't support out-by-reference parameters? (or ref parameters?) That's a limitation of the CLR. We chose to implement async methods in a similar way to iterator methods -- i.e. through the compiler transforming the method into a state-machine-object. The CLR has no safe way to store the address of an "out parameter" or "reference parameter" as a field of an object. The only way to have supported out-by-reference parameters would be if the async feature were done by a low-level CLR rewrite instead of a compiler-rewrite. We examined that approach, and it had a lot going for it, but it would ultimately have been so costly that it'd never have happened.

这种情况的典型解决方法是让异步方法返回一个元组。 您可以这样重写您的方法:

public async Task Method1()
{
    var tuple = await GetDataTaskAsync();
    int op = tuple.Item1;
    int result = tuple.Item2;
}

public async Task<Tuple<int, int>> GetDataTaskAsync()
{
    //...
    return new Tuple<int, int>(1, 2);
}

关于c# - 如何编写不带 out 参数的异步方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18716928/

相关文章:

c# - Unity 3D 在 GetButtonDown 上的特定时间移动对象

node.js - Typeerror 回调不是 Nodejs 中的函数

c# - 使用 HttpClient 进行异步文件下载

javascript - 等待/异步不在 for 循环中工作

asynchronous - 如何等待 Rust 中的异步函数调用列表?

c# - 如果 Powershell 构建在 .Net 之上,那么编写脚本而不是 C# 代码的原因是什么?

c# - 将文本从文本文件添加到 PDF 文件

c# - Task.Run 与 Invoke() 区别

c# - 如何从第二个 API 调用返回相同的状态代码

c# - 匿名类型如何有用的一些例子是什么?