如何写出来与参数异步方法? [英] How to write a async method with out parameter?

查看:99
本文介绍了如何写出来与参数异步方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个异步方法与退出参数,如:

I want to write a async method with an out parameter, like this:

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

我如何在 GetDataTaskAsync

推荐答案

您不能有异步方法REF 退出参数。

卢西恩Wischik解释了为什么这是不可能在这个MSDN主题:<一href=\"http://social.msdn.microsoft.com/Forums/en-US/d2f48a52-e35a-4948-844d-828a1a6deb74/why-async-methods-cannot-have-ref-or-out-parameters\">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

至于为什么异步方法不支持外通过定位参数?
  (或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.

对于这种情况的一个典型的解决方法是让异步方法返回一个元组来代替。
你可以重新写你的方法这样:

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 void 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):
}

这篇关于如何写出来与参数异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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