Say I have a class that needs to perform some async initialization using an InitializeAsync() method. I want to make sure that the initialization is performed only once. If
I'd go with AsyncLazy
public class AsyncLazy : Lazy>
{
public AsyncLazy(Func valueFactory) :
base(() => Task.Run(valueFactory)) { }
public AsyncLazy(Func> taskFactory) :
base(() => Task.Run(() => taskFactory())) { }
public TaskAwaiter GetAwaiter() { return Value.GetAwaiter(); }
}
And consume it like this:
private AsyncLazy asyncLazy = new AsyncLazy(async () =>
{
await DoStuffOnlyOnceAsync()
return true;
});
Note i'm using bool
simply because you have no return type from DoStuffOnlyOnceAsync
.
Edit:
Stephan Cleary (of course) also has an implementation of this here.