gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:36:18 25 4
gpt4 key购买 nike

我想用 out 写一个异步方法参数,像这样:

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

我如何在 GetDataTaskAsync 中执行此操作?

最佳答案

您不能使用 ref 使用异步方法或 out参数。

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/47707984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com