Asynchrony and Out Parameters: A Dilemma
Developers often encounter the need to write asynchronous methods with output parameters, but the .NET framework poses a challenge in this regard.
The Issue
The following code snippet illustrates the problem:
public async void Method1() { int op; int result = await GetDataTaskAsync(out op); }
This code attempts to create an async method with an output parameter, but such a feature is unavailable in the .NET Framework.
The Reasoning
According to Lucian Wischik, a Microsoft engineer, this limitation stems from the way async methods are implemented in the CLR. They are transformed by the compiler into state-machine-objects, which lack a safe mechanism for storing the address of out or reference parameters.
Workaround
A common workaround is to have the async method return a Tuple:
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); }
This approach provides a way to pass multiple values back from the async method without resorting to out parameters.
The above is the detailed content of How Can I Use Output Parameters with Asynchronous Methods in .NET?. For more information, please follow other related articles on the PHP Chinese website!