Thursday, February 15, 2018

Open.Linq.AsyncExtensions (was a bit trickier than I thought it would be)

https://www.nuget.org/packages/Open.Linq.AsyncExtensions/

Maybe you have a method that returns Task<IEnumerable<T>>. And possibly this return comes from a chain of methods so you might have something like this:

return X .Y() .Z() 

But you end up needing some filter from the results. Then you have to have this:

return (await X .Y() .Z()) .Where(filter); 

Instead, wouldn't it be better to write this:

return X .Y() .Z() .Where(filter) 

At first I thought it'd be easy to take the System.Linq definition and retool it to have all the methods have (await source).X() versions.

Of course this would only be worth it if type inference did it's thing and for Task<IEnumerable<T>>. Which it did.

But for Task<List<T>> (or any other sub-class) it did not recognize the more specific definition. Using type constraints and other magic tricks did no good to solve this problem.

At least for now, the simple solution was to create specific .AsEnumerable() extensions for List<T> and other common collections.

Now I can write methods that return tasks without writing the async/await every time. :)

Currently using in conjunction with: https://www.nuget.org/packages/Open.Database.Extensions/


Note: This is not meant to replace AsyncEnumerable.

As the ReactiveX/Ix extensions are meant to be iteratively asynchronous (deferred foreach). Once a block of data (list, etc) is acquired, synchronous non-blocking operations don't incur any additional overhead and it's not adding any benefit to make each iteration asynchronous. The asynchronous benefit of asynchronous enumerable comes in when there's asynchronous pauses between iterations.

Open.Linq.AsyncExtensions (was a bit trickier than I thought it would be) Click here
  • Blogger Comment
  • Facebook Comment

0 comments:

Post a Comment

The webdev Team