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;
});
}
Is it possible to await an async method within a Func?
No, to use async the method needs to return
Task
Task<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 CacheManager
to accept a Func<Task<string>>
, as well as return a Task<string>
. And change GetBearerToken
to return Task<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
async () => (await _directConnectTokenApi.Post<DirectConnectTokenResponse>()).Token