Skip to content

Instantly share code, notes, and snippets.

@johnazariah
Created April 19, 2020 17:12
Show Gist options
  • Save johnazariah/ab269f7e005d538ed706b7a9cdb15bf1 to your computer and use it in GitHub Desktop.
Save johnazariah/ab269f7e005d538ed706b7a9cdb15bf1 to your computer and use it in GitHub Desktop.
Simple LazyAsync
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();
}
}
@ericrey85
Copy link

ericrey85 commented Apr 24, 2020

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment