'async/await "List<> does not contain a definition for 'GetAwaiter'"

I apologize for sounding dense, but I swear I have read up on async/await and played with examples, but I am still stumped at simple things like why the following code is giving me error:

        [HttpGet("{includeInactive}")]
        public async Task<List<Torrent>> GetTorrentsAll(bool includeInactive)
        {
            List<Torrent> torrentsAll = await _cacheStore.GetCachedTorrentsAll();

            //...potentially filter torrentsAll here

            return torrentsAll;
        }

So _cacheStore.GetCachedTorrentsAll() is not an async function. It's just a function that potentially might be taking a while in the database, so I was trying to ensure that it's not blocking. I thought that awaiting it within the async web API was the way to go about that. But I get confusing error under the await _cacheStore.GetCachedTorrentsAll() line that says 'List does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'List' could be found (are you missing a using directive or an assembly reference?).

I am very confused by this.



Solution 1:[1]

So _cacheStore.GetCachedTorrentsAll() is not an async function. It's just a function that potentially might be taking a while in the database, so I was trying to ensure that it's not blocking.

It is reasonable to make it asynchronous, then.

I guess maybe since _cacheStore.GetCachedTorrentsAll() is not async, it will still block the thread regardless (?)

This is correct. Synchronous methods - by definition - block the calling thread until they complete.

In which case async/await seems like a rabbit hole to me,

It can be. In this case, you have correctly identified an operation that should be asynchronous (i.e., I/O-bound). But just sticking an async on the controller method isn't going to help; that's actually the last step in making this asynchronous.

The first step is to identify the lowest-level API that should be asynchronous. E.g., the database query. Make that call use the asynchronous database API first, use await, and make that method async. Then let async/await grow from that method up through your app. It will eventually end up at the controller method, and then you can make that async.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stephen Cleary