0

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?

closed as off-topic by Greg Burghardt, gnat, BobDalgleish, Machado, ChrisF Feb 3 at 18:39

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions asking for assistance in explaining, writing or debugging code are off-topic here. These can be asked on Stack Overflow if they include the desired behavior, a specific problem or error, and the shortest code necessary to reproduce it in the question (see Minimal, Complete, and Verifiable Example)." – Greg Burghardt, gnat, BobDalgleish, Machado, ChrisF
If this question can be reworded to fit the rules in the help center, please edit the question.

4

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.

  • " 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 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 at 14:22
  • That's right you cannot traverse IEnumerable asynchronously but it may initiate synchronous IO or some heavy computations. – max630 Jan 21 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 at 10:45

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