如何编写带有 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
中执行此操作?
How do I do this in GetDataTaskAsync
?
推荐答案
不能有带有 ref
或 out
参数的异步方法.
You can't have async methods with ref
or out
parameters.
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
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
至于为什么 async 方法不支持 out-by-reference 参数?(或 ref 参数?)这是 CLR 的限制.我们选择了以与迭代器方法类似的方式实现异步方法——即通过编译器将方法转换为状态机对象.CLR 没有安全的方法来存储地址输出参数"或参考参数"作为对象的字段.支持 out-by-reference 参数的唯一方法是如果异步功能是通过低级 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.
这种情况的典型解决方法是让异步方法返回一个元组.你可以这样重写你的方法:
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屋!