2Fast4YouBR 2Fast4YouBR - 27 days ago 8
C# Question

Is this really Async ? IEnumerable<T> Extention

public static async Task<T> FirstIfNotNullOrEmptyAsync<T>(this Task<IEnumerable<T>> obj) where T : class
{
var first = await Task.WhenAny(obj);

return first?.Result?.FirstOrDefault() ?? null;
}


Here are the 2 others methods to show the complete

***Main Method*** (in this case will return only item in the collection or a collection empty)
private async Task<IEnumerable<T>> fetchRecordsAsync(SqlCommand SqlCommand, bool isSingleRecord)
{..some code...}

***here is the caller*** that will get the collection and pass only T
protected async Task<T> GetSingleRecord(SqlCommand SqlCommand)
{
return await fetchRecordsAsync(SqlCommand, true).FirstIfNotNullOrEmptyAsync();
}


Is this the correct way to work with async extentions of IEnumerable or it will be doing a sync?

Do I really need create another task (first)?

cheers

Answer

Is this really Async ?

Yes it is. Task.WhenAny will return the first task that completes. Using .Result on such task (a completed one) will not cause a synchronous wait.

BTW, you don't need to use Task.WhenAny, your method can be simplified like this:

public static async Task<T> FirstIfNotNullOrEmptyAsync<T>(
    this Task<IEnumerable<T>> obj) where T : class
{
    var result = await obj;

    return result?.FirstOrDefault();
}
Comments