Have you ever wondered if there was an async yield return in C#? Well, there is an async yield return and in this video, I’ll show you how to use the yield return statement asynchronously in C#.

When you use the yield return statement in your code, you indicate that the method, operator, or get accessor in which the yield return keyword appears is an iterator. The yield return statement will return one one element in a collection at a time.

The result returned from a yield return iterator method can be consumed by using a foreach statement or LINQ query. Each iteration of the foreach loop calls the iterator method. When a yield return statement is reached in the iterator method, the result is returned and the current location in the iterator method is retained. Upon the execution of the next element in the foreach loop, the iterator method is restarted from the retained location the next time that the iterator method is called.

When working with asynchronous code using async/await, the use of the yield return statement requires just a few small adjustments to your code. Using an async yield return statement requires that the method be asynchronous, making use of async/await.

Usually an async method will return a task. Your first thought when using yield return in your async method may be to have the method return Task of IEnumerable. However, this is not allowed when using yield return, instead your async yield return method must return an IAsyncEnumerable.

You also cannot wait your new async yield return method that returns an IAsynEnumerable. Instead, yo must await the “foreach” statement instead. This is becuase IAsyncEnumerable does not have a GetAwaiter() method. IAsyncEnumerable is an async iterator.

Hopefully this video will help clear up the async yield return usage.

GitHub link: https://github.com/brianlagunas/YieldReturnAsync

Be sure to watch my new Pluralsight course “Introduction to Prism for WPF”:
📺 http://bit.ly/PrismForWpf

Sponsor Me on GitHub:
🙏🏼 http://bit.ly/SponsorBrianOnGitHub

Get 2 Free Stocks on WeBull (Valued up to $1600 when you deposit $100)
💰 http://bit.ly/BrianWeBull

Follow Me:
🐦 Twitter: http://bit.ly/BrianLagunasOnTwitter

Brian Lagunas

View all posts

Follow Me

Follow me on Twitter, subscribe to my YouTube channel, and watch me stream live on Twitch.