gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:32:30 28 4
gpt4 key购买 nike

我想写一个带有 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/

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