Last active
October 11, 2021 10:48
-
-
Save tormodfj/33e216dd9c34c7160f3ebe0f7dad8526 to your computer and use it in GitHub Desktop.
AsyncLazy<T>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Async edition of <see cref="Lazy{T}"/>. | |
/// </summary> | |
/// <typeparam name="T">The type of the lazily initialized value</typeparam> | |
public class AsyncLazy<T> : Lazy<Task<T>> | |
{ | |
public AsyncLazy(Func<T> valueFactory) | |
: base(() => Task.Run(valueFactory)) { } | |
public AsyncLazy(Func<Task<T>> asyncValueFactory) | |
: base(() => Task.Run(asyncValueFactory)) { } | |
/// <summary> | |
/// Gets a value that indicates whether a value has been created. | |
/// </summary> | |
public new bool IsValueCreated => base.IsValueCreated && Value.IsCompletedSuccessfully; | |
/// <summary> | |
/// Gets the value syncronously, if it is created. Otherwise returns <see langword="default"/>. | |
/// </summary> | |
public T? ValueOrDefault => IsValueCreated ? Value.Result : default; | |
/// <summary> | |
/// Gets an awaiter used to await the lazy value. | |
/// </summary> | |
public TaskAwaiter<T> GetAwaiter() => Value.GetAwaiter(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment