/// <summary> /// Initializes a new instance of the <see cref="AsyncLazy<T>"/> class. /// </summary> /// <param name="factory">The asynchronous delegate that is invoked to produce the value when it is needed. May not be <c>null</c>.</param> public AsyncLazy(Func <Task <T> > factory, AsyncLazyFlags flags = AsyncLazyFlags.None) { var func = factory; if ((flags & AsyncLazyFlags.ExecuteOnThreadPool) == AsyncLazyFlags.ExecuteOnThreadPool) { func = () => System.Threading.Tasks.Task.Run(factory); } _instance = new Lazy <Task <T> >(func); }
/// <summary> /// Initializes a new instance of the <see cref="AsyncLazy<T>"/> class. /// </summary> /// <param name="factory">The asynchronous delegate that is invoked to produce the value when it is needed. May not be <c>null</c>.</param> /// <param name="flags">Flags to influence async lazy semantics.</param> public AsyncLazy(Func <Task <T> > factory, AsyncLazyFlags flags = AsyncLazyFlags.None) { var f = factory ?? throw new ArgumentNullException(nameof(factory)); if ((flags & AsyncLazyFlags.ExecuteOnCallingThread) != AsyncLazyFlags.ExecuteOnCallingThread) { f = RunOnThreadPool(f); } _mutex = new object(); _instance = new Lazy <Task <T> >(f); }
/// <summary> /// Initializes a new instance of the <see cref="AsyncLazy<T>"/> class. /// </summary> /// <param name="factory">The asynchronous delegate that is invoked to produce the value when it is needed. May not be <c>null</c>.</param> /// <param name="flags">Flags to influence async lazy semantics.</param> public AsyncLazy(Func <Task <T> > factory, AsyncLazyFlags flags = AsyncLazyFlags.None) { _factory = factory ?? throw new ArgumentNullException(nameof(factory)); if ((flags & AsyncLazyFlags.RetryOnFailure) == AsyncLazyFlags.RetryOnFailure) { _factory = RetryOnFailure(_factory); } if ((flags & AsyncLazyFlags.ExecuteOnCallingThread) != AsyncLazyFlags.ExecuteOnCallingThread) { _factory = RunOnThreadPool(_factory); } _mutex = new object(); _instance = new Lazy <Task <T> >(_factory); }
public AsyncLazy(Func <Task <TResult> > func, AsyncLazyFlags flag = AsyncLazyFlags.None) { if (func == null) { throw new ArgumentNullException(nameof(func)); } _factory = func; if ((flag & AsyncLazyFlags.RetryOnFailure) == AsyncLazyFlags.RetryOnFailure) { _factory = RetryOnFailure(_factory); } if ((flag & AsyncLazyFlags.ExecuteOnCallingThread) != AsyncLazyFlags.ExecuteOnCallingThread) { _factory = RunOnThreadPool(_factory); } _mutex = new object(); _instance = new Lazy <Task <TResult> >(func); }
/// <summary> /// startLazy is only for demo purpose ;-) /// </summary> public ObjectWithLazy(bool startLazy, AsyncLazyFlags asyncLazyFlags = AsyncLazyFlags.None) { _lazyNumber1 = new AsyncLazy <int>(async() => { await Task.Delay(1500).ConfigureAwait(false); return(42); }); _lazyNumber2 = new AsyncLazy <int>(async() => { await Task.Delay(1500).ConfigureAwait(false); return(42); }); if (startLazy) { _lazyNumber1.Start(); _lazyNumber2.Start(); } }