maca88 / AsyncGenerator

Generating async c# code using Roslyn
MIT License
47 stars 16 forks source link

Add option to generate async-over-sync templates #172

Open hazzik opened 8 months ago

hazzik commented 8 months ago

I've came up with following helper that simplifies the code that might be generated:

class AsyncHelper 
{
    public static Task<TResult> CallAsync<TResult>(Func<TResult> func, CancellationToken cancellationToken = default)
    {
        if (cancellationToken.IsCancellationRequested)
            return Task.FromCanceled<TResult>(cancellationToken);

        try { return Task.FromResult(func()); }
        catch (Exception ex) { return Task.FromException<TResult>(ex); }
    }

        // These are methods for all Func<...,TResult>, Action<...> delegates.
    public static Task<TResult> CallAsync<T1, TResult>(
        Func<T1, TResult> func, 
        T1 arg1,
        CancellationToken cancellationToken = default)
    {
        return CallAsync(F, cancellationToken);

        TResult F() => func(arg1);
    }
}

And so, any sync function can be turned to async like this:

public Task<ICollection> GetOrphansAsync(object snapshot, string entityName, CancellationToken cancellationToken) =>
    AsyncHelper.CallAsync(GetOrphans, snapshot, entityName, cancellationToken);

So it would be nice to have control over how the async-over-sync functions are generated.