Is it possible to await an async method within a Func<string>?
Here's my code. You can see in the comment what I'd like to be able to do:
private static string GetBearerToken()
{
return CacheManager.Get<string>(
"DirectConnectApi_BearerToken",
() =>
{
var response = _directConnectTokenApi
.Post<DirectConnectTokenResponse>()
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
//I want to do this instead:
//var response = await _directConnectTokenApi.Post<DirectConnectTokenResponse>().ConfigureAwait(false);
return response.result.Token;
});
}
No, to use async the method needs to return
TaskTask<T>ValueTask)None of these values is a string, so neither option is compatible with a method just returning a string.
So you will need to change the
CacheManagerto accept aFunc<Task<string>>, as well as return aTask<string>. And changeGetBearerTokento returnTask<string>, and any method calling that, and so on. This is inherent to async/await, it tend to "spread", affecting most of the code base. If this is a problem or a feature is somewhat controversial.If you do that you should just be able to write