Skip to content

Instantly share code, notes, and snippets.

@cajuncoding
Last active September 21, 2023 01:36
Show Gist options
  • Save cajuncoding/1ad96ff107986a4c7ab51d56c695b262 to your computer and use it in GitHub Desktop.
Save cajuncoding/1ad96ff107986a4c7ab51d56c695b262 to your computer and use it in GitHub Desktop.
Ultra lightweight AsyncLazy<T> Wrapper for Lazy<T>
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace CajunCoding
{
/// <summary>
/// Greatly Simplified lightweight wrapper class to support improved code readability and management of
/// Async methods used in combination with Lazy&lt;T&gt; wrapper for thread safe lazy loading from a Func value factory!
/// Based on Original blogs here:
/// https://blogs.msdn.microsoft.com/pfxteam/2011/01/15/asynclazyt/
/// And on the much more robust NittoEx.AsyncLazy<T> class here:
/// https://github.com/StephenCleary/AsyncEx/blob/master/src/Nito.AsyncEx.Coordination/AsyncLazy.cs
///
/// (c) 2017 Brandon Bernard (CajunCoding)
/// This code is licensed under MIT license - For license details see: https://opensource.org/license/mit/
/// </summary>
/// <typeparam name="T"></typeparam>
public class AsyncLazy<T> : Lazy<Task<T>>
{
public AsyncLazy(Func<Task<T>> taskFactory) : base(taskFactory) {}
public TaskAwaiter<T> GetAwaiter() => Value.GetAwaiter();
public ConfiguredTaskAwaitable<T> ConfigureAwait(bool continueOnCapturedContext)
=> Value.ConfigureAwait(continueOnCapturedContext);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment