Pregunta

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?

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
scroll top