0

How do I Lazy load the Bars collection using async-await? It must take an Id from the MyClass instance to get the specific collection back.

  public class MyClass {
    public int Id { get; set; }
    public Lazy<List<Bar>> Bars { get; private set; }

    public MyClass() {
      Bars = new Lazy<List<Bar>>(async () => await LoadBars(), true);
    }

    private async Task<List<Bar>> LoadBars() {
      return await Util.Database.GetBarsAsync(Id);
    } 
  }

This collection consumes a lot of memory so I only want it loaded when I need it.

The error I get is on the =>:

Cannot convert async lambda expression to delegate type 'Func>'. An async lambda expression may return void, Task or Task, none of which are convertible to 'Func>'

sprocket12
  • 5,368
  • 18
  • 64
  • 133
  • Simply you can't ... you may use `Lazy>> Bars {get;private set;} => new Lazy>>( () => LoadBars(), true)` and `await Bars.Value` – Selvin Apr 16 '19 at 12:52

1 Answers1

1

Short answer; you can't (without various tricks), but you can instead do this:

public class MyClass {
    public int Id { get; set; }
    public Lazy<Task<List<Bar>>> Bars { get; private set; }

    public MyClass() {
      Bars = new Lazy<Task<List<Bar>>>(() => LoadBars(), true);
    }

    private Task<List<Bar>> LoadBars() {
      return Util.Database.GetBarsAsync(Id);
    } 

    private async SomethingElseAsync() {
        List<Bar> bars = await Bars.Value;
    }
}
sellotape
  • 8,034
  • 2
  • 26
  • 30