Home > Enterprise >  How do I make an async method return Task<IEnumerable<T>>?
How do I make an async method return Task<IEnumerable<T>>?

Time:01-06

I am currently refactoring a method that has the async keyword but does not use await, thus running synchronously.

private async Task<IEnumerable<Obj>> SearchObj(string value)
    {
        if (string.IsNullOrEmpty(value))
            return _db.Objects;

        return _db.Objects.AsEnumerable().Where(x => x.SomeProperty.Contains(value, StringComparison.InvariantCultureIgnoreCase));
    }

How do I modify this method so that it runs asynchronously? Is it even necessary to run this asynchronously given a large dataset?

I have tried using the AsAsyncEnumerable() method but am not sure how to execute the Where() filter on an IAsyncEnumerable object.

CodePudding user response:

Don't use AsEnumerable. Use one of the *Async() Methods:

private async Task<IEnumerable<Obj>> SearchObj(string value)
{
    if (string.IsNullOrEmpty(value))
        return await _db.Objects.ToListAsync();

    return await _db.Objects.Where(x => x.SomeProperty.Contains(value, StringComparison.InvariantCultureIgnoreCase)).ToListAsync();
}

CodePudding user response:

AsEnumerable is not async method and it is needed to use ToListAsync, ToArrayAsync before returning IEnumerable. Also note that .Contains(value, StringComparison.InvariantCultureIgnoreCase) overload translation is not supported. Just use .Contains(value), if default collation in database is case insensitive, it will work by default.

private Task<IEnumerable<Obj>> SearchObj(string value)
{
    var query = _db.Objects.AsQueryable();

    if (!string.IsNullOrEmpty(value))
        query = query.Where(x => x.SomeProperty.Contains(value));

    return query.ToListAsync();
}
  • Related