1

I'm using a lot of async Task<IEnumerable<T>> methods and I want to stop doing this everytime to get the items as a list:

var items = await AsyncMethodThatReturnsEnumerable();
var enumeratedItems = items.ToList();

So, if I do something like this

var items = (await AsyncMethodThatReturnsEnumerable()).ToList()

Will it run asynchronously?

| improve this question | | | | |
5

Yes. Your code is equivalent to this:

var value = await AsyncMethodThatReturnsEnumerable(); // this is asynchronous
var list = value.ToList(); // this is _not_ asynchrounous

All you have done is written that on one line without the variable value in between. As long as your IEnumerable<T> is reasonably sized, then you probably won't notice the delay of iterating everything into a List<T>.

The await keyword is like a bookmark, so when the asynchronous method is done, you are returned to the thread context you called the method from. During the time the asynchronous method is running the calling thread is not blocked.

| improve this answer | | | | |
  • " As long as your IEnumerable<T> is reasonably sized, then you probably won't notice the delay of iterating everything into a List<T>" this is up to to the concrete implementation, it could be so that getting only one element or even stepping to the end might be quite noticeable. – max630 Jan 20 '19 at 8:24
  • To my knowledge you can't mix async and yield return which means the IEnumerable<T> is usually pre-populated when you get it. – Berin Loritsch Jan 20 '19 at 14:22
  • That's right you cannot traverse IEnumerable asynchronously but it may initiate synchronous IO or some heavy computations. – max630 Jan 21 '19 at 6:35
  • @max630 the question asks "are these equivalent". They may be equivalently slow, at which point you can investigate changing to Task<IEnumerable<Task<T>>> or somesuch – Caleth Jan 21 '19 at 10:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.