Bob Swager
Bob Swager

Reputation: 892

fill static property from async method

I want to fill this list of MyModel with async method. The async method returns List of MyModel.

I want to call MyClass.list in other functions.

Code :

 public static class MyClass
    {
       public static List<MyModel> list= await MyHelper.GetCache();

I'm getting an error :

Severity Code Description Project File Line Suppression State Error CS1992 The 'await' operator can only be used when contained within a method or lambda expression marked with the 'async' modifier

Any idea ?

Upvotes: 0

Views: 2184

Answers (2)

Fabio
Fabio

Reputation: 32443

Based on your environment using .Wait() will possible cause a deadlock (Desktop or ASP.NET applications)

Another approach will be create "lazy" loading method which return required list.

private static List<MyModel> MyModelInternal;
public static async Task<List<MyModel>> GetMyModelAsync()
{
    if (MyModelInternal == null)
    {
        MyModelInternal = await MyHelper.GetCacheAsync();
    }

    return Task.FromResult(MyModelInternal);
}

In case when internal list already initiated method will return complete task.

Or if you have some UI method where you can execute asynchronous method, then you can initialize your list there.

Upvotes: 1

bradgonesurfing
bradgonesurfing

Reputation: 32202

You can't use await in a static initializer like that. But you can block and wait for the result

public static class MyClass
    {
       public static List<MyModel> list= MyHelper.GetCache().Wait()

Upvotes: 1

Related Questions