How can I await an async method within a Func<string>?

90 Views Asked by At

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;
            });

    }
1

There are 1 best solutions below

0
JonasH On BEST ANSWER

Is it possible to await an async method within a Func?

No, to use async the method needs to return

  1. void
  2. Task
  3. Task<T>
  4. Something that looks like a task (like 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