C# GetOnce

Date: 2024-01-31
public class GetOnce<T>
{
    private readonly Func<Task<T>> fn;
    private Task<T> dataTask = null;

    public GetOnce(Func<Task<T>> initialFn)
    {
        fn = initialFn;
    }

    public async Task<T> Get()
    {
        dataTask ??= fn();
        return await dataTask;
    }
}

// Example
public class Program
{
    public static GetOnce<string> Content = new(() => { Console.WriteLine("ReadingFile"); return File.ReadAllTextAsync(@"C:\test.txt"); });

    public static async Task Main()
    {
        Console.WriteLine(await Content.Get());
        Console.WriteLine(await Content.Get());
    }
}
82370cookie-checkC# GetOnce