Return Multiple Values from Async Method
Async method cannot have Ref or an Out parameters. So, we cannot pass back data from them through typical syntax. This requires us to be a little creative.
One way around this CLR limitation is to use tuples.
Specifically, we can use an implicit tuple, that will give us named properties.
The following is an example of an async method that we want a success response, as well as, some data.
private async Task<(int ReturnStatus, List<string> ResultData)> TryLogin(OpenIdConnectRequest request)
{
return (-3, new List<string>());
}
The above call returns a tuple that contains two values: a return status value and a list of results.
The list is what we would normally have passed back via an Out parameter.
But, the above method returns both properties by tuple. And, each property is named, unlike old-school tuple.
So, the above method can be used like this:
var foo = await TryLogin;
if(foo.ReturnStatus != 1)
{
// Failed to login.
return -1;
}
// If here, the login was successful.
// Get the result data...
var rd = foo.ResultData;
No Comments