Created
April 19, 2020 17:12
-
-
Save johnazariah/ab269f7e005d538ed706b7a9cdb15bf1 to your computer and use it in GitHub Desktop.
Simple LazyAsync
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
namespace Utility | |
{ | |
using System; | |
using System.Runtime.CompilerServices; | |
using System.Threading.Tasks; | |
internal sealed class LazyAsync<T> | |
{ | |
public T Value => valueL.Value; | |
private readonly Lazy<Task<T>> instance; | |
private readonly Lazy<T> valueL; | |
// private constructor which sets both fields | |
private LazyAsync(Lazy<Task<T>> instance) | |
{ | |
this.instance = instance; | |
this.valueL = new Lazy<T>(() => this.instance.Value.GetAwaiter().GetResult()); | |
} | |
/// <summary> | |
/// Constructor for use with synchronous factories | |
/// </summary> | |
public LazyAsync(Func<T> synchronousFactory) | |
: this(new Lazy<Task<T>>(() => Task.Run(synchronousFactory))) | |
{ } | |
/// <summary> | |
/// Constructor for use with asynchronous factories | |
/// </summary> | |
public LazyAsync(Func<Task<T>> asynchronousFactory) | |
: this (new Lazy<Task<T>>(() => Task.Run(asynchronousFactory))) | |
{ } | |
public TaskAwaiter<T> GetAwaiter() => | |
instance.Value.GetAwaiter(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is cool John. I needed a way to create an async and lazily executed pipeline in C#, and I came up with an implementation you can find in the link below. Let me know what you think!
https://gist.github.com/ericrey85/da9671a22234ef981e5ee3653face4af