1

I have to non-static DoStuffOnlyOnceAsync method which I'm trying to call using AsyncLazy, but I'm getting error.

How to call non-static method?

A field initializer cannot reference the non-static field, method, or property 'TestClass.DoStuffOnlyOnceAsync()'

 using System;
 using System.Runtime.CompilerServices;
 using System.Threading.Tasks;

 namespace Registry
{
public class AsyncLazy<T> : Lazy<Task<T>>
{
    public AsyncLazy(Func<T> valueFactory) : base(() => Task.Run(valueFactory)) { }

    public AsyncLazy(Func<Task<T>> taskFactory) : base(() => Task.Run(() => taskFactory())) { }

    public TaskAwaiter<T> GetAwaiter() { return Value.GetAwaiter(); }
}
public class TestClass
{
    private AsyncLazy<bool> asyncLazy = new AsyncLazy<bool>(async () =>
    {
        await DoStuffOnlyOnceAsync();
        return true;
    });

    public TestClass() { }

    public async Task DoStuffOnlyOnceAsync()
    {
        await Task.FromResult(false);
    }
}
}
user584018
  • 10,186
  • 15
  • 74
  • 160
  • Would it be correct to guess that the code in your question is different from what you're actually working with? Because if this was it, you could just make `DoStuffOnlyOnceAsync` a `static` method. I'm guessing there's some reason why you're avoiding that. Does that method depend on other instance members? – Scott Hannen Apr 01 '19 at 15:52

1 Answers1

2

The limitation is that the field initializer cannot call any non-static methods. This is true for any field initializer, and has nothing to do with AsyncLazy<T> or async.

To fix it, initialize the field in your constructor:

public TestClass()
{
  asyncLazy = new AsyncLazy<bool>(async () =>
  {
    await DoStuffOnlyOnceAsync();
    return true;
  });
}
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810