Reading Large Data files in WPF with IAsyncEnumerable

 


Producing and consuming Async sequences

Reading Large Data files in WPF

As soon as you type new Thread(), it’s over; your project already has legacy code.

An asynchronous foreach will ask the collection object for an enumerator, and will repeatedly ask it to advance to the next item, executing the loop body with the value returned by Current each time, until the enumerator indicates that there are no more items. 

The main difference is that the synchronous MoveNext has been replaced by MoveNextAsync, which returns an awaitable ValueTask<T>. (The IAsyncEnumerable<T> interface also provides support for passing in a cancellation token, although an asynchronous foreach won’t use that itself.)

To consume an enumerable source that implements this pattern, you must put the await keyword in front of the foreach. You can also return an IAsyncEnumerable<T>.  Code below shows both implementation and consumption of IAsyncEnumerable<T> in action.

TEST 1: Reading stream line by line using IAsyncEnumerable

Reading large 326MB text file 3MLN line by line and displaying in WPF TextBox







Reference to the System.Linq.Async package, and add a using System.Linq; declaration, all the LINQ operators will be available on IAsyncEnumerable<T> expressions.