2
votes

I have a basic singleton class, but the singleton has an async method like so:

public sealed class AddInHandler
{
    private static readonly AddInHandler instance = new AddInHandler();

    static AddInHandler()
    {
    }

    AddInHandler()
    {
    }

    public static AddInHandler Instance
    {
        get { return instance.Value; }
    }

    public async Task<AvailableActions> GetAvailableActions(string carrierMnemonic)
    {
        // some code that uses await...
    }
}

If I try to use the async method via the singleton, e.g:

public async Task<Collection<CarrierInformation>> RetrieveAvailableCarriersAsync()
{
    // some await code here

    await Task.Run(() => 
    {
        // ...
        var availableActions = await AddInHandler.Instance.GetAvailableActions(addIn.Name);
    }
}

Then I hit error.

The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.

I'm expecting it's because the Instance property isn't async that I'm having this issue? Is this correct, and is there a recommended best approach for resolving this?

2
Please show the full context for your call. You can only use await within an asynchronous function - either an async method, or an async lambda expression. I strongly suspect that's the problem. - Jon Skeet
I think it is complaining about the method wrapping this code var availableActions = await AddInHandler.Instance.GetAvailableActions(addIn.Name);. That method needs to be marked as async - Helic

2 Answers

4
votes

I'm expecting it's because the Instance property isn't async that I'm having this issue?

No, you're simply missing the async modifier inside the lambda expressions declaration. The lambda itself has to be marked as async in order for the compiler to use await inside it:

await Task.Run(async () => 
{
    // ...
    var availableActions = await AddInHandler.Instance.GetAvailableActions(addIn.Name);
}

The documentation is pretty straight forward:

Use the async modifier to specify that a method, lambda expression, or anonymous method is asynchronous. If you use this modifier on a method or expression, it's referred to as an async method.

2
votes

If you're calling

var availableActions = await AddInHandler.Instance.GetAvailableActions(addIn.Name);

in an expresion of type new Action(() =>{}); then you need the async modifier.

new Action( async () =>
   {
      // some await code
   });