PaulG
PaulG

Reputation: 14021

Calling async method behind Singleton.Instance

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?

Upvotes: 2

Views: 2605

Answers (2)

Yannick Excoffier
Yannick Excoffier

Reputation: 81

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

Upvotes: 2

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

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.

Upvotes: 4

Related Questions