AsyncGenerator icon indicating copy to clipboard operation
AsyncGenerator copied to clipboard

Add option to generate async-over-sync templates

Open hazzik opened this issue 1 year ago • 0 comments

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.

hazzik avatar Mar 26 '24 11:03 hazzik