如何编写带有out参数的异步方法? [英] How to write an async method with out parameter?
问题描述
我想编写一个带有out
参数的异步方法,如下所示:
I want to write an async method with an out
parameter, like this:
public async void Method1()
{
int op;
int result = await GetDataTaskAsync(out op);
}
如何在GetDataTaskAsync
中执行此操作?
推荐答案
您不能具有带有ref
或out
参数的异步方法.
You can't have async methods with ref
or out
parameters.
Lucian Wischik解释了为什么无法在此MSDN线程上做到这一点:
Lucian Wischik explains why this is not possible on this MSDN thread: http://social.msdn.microsoft.com/Forums/en-US/d2f48a52-e35a-4948-844d-828a1a6deb74/why-async-methods-cannot-have-ref-or-out-parameters
至于为什么异步方法不支持按引用引用的参数? (或ref参数?)这是CLR的局限性.我们选择 以类似于迭代器方法的方式实现异步方法-即 通过编译器将方法转换为 状态机对象. CLR没有安全的方法来存储地址 输出参数"或参考参数"作为对象的字段. 支持外部参考参数的唯一方法是 异步功能是通过低级CLR重写而不是 编译器重写.我们研究了这种方法,并且还有很多事情要做 为此,但最终成本会非常高昂,以至于从来没有 发生了.
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.
这种情况的典型解决方法是让async方法返回一个Tuple. 您可以这样重写方法:
A typical workaround for this situation is to have the async method return a Tuple instead. You could re-write your method as such:
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);
}
这篇关于如何编写带有out参数的异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!