PaulG PaulG - 2 months ago 16
C# Question

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?

Answer

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.