Skip to content

Instantly share code, notes, and snippets.

@tormodfj
Last active October 11, 2021 10:48
Show Gist options
  • Save tormodfj/33e216dd9c34c7160f3ebe0f7dad8526 to your computer and use it in GitHub Desktop.
Save tormodfj/33e216dd9c34c7160f3ebe0f7dad8526 to your computer and use it in GitHub Desktop.
AsyncLazy<T>
/// <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