Great tweet from Oleg Kyrylchuk (follow him!) showing how cool Parallel.ForEachAsync is in .NET 6. It’s new! Let’s look at this clean bit of code in .NET 6 that calls the public GitHub API and retrieves n number of names and bios, given a list of GitHub users: using System.Net.Http.Headers; Let’s note a few things in this sample Oleg shared. First, there’s no Main() as that’s not required (but you can have it if you want). We also see just two usings, bringing other namespaces into scope. Here’s what it would look like with explicit namespaces: using System; We’ve got an array of users to look up in userHandlers. We prep an HttpClient and setup some ParallelOptions, giving our future ForEach the OK to “fan out” to up to three degrees of parallelism - that’s the max number of concurrent tasks we will enable in one call. If it’s -1 there is no limit to the number of concurrently running operations. The really good stuff is here. Tight and clean: await Parallel.ForEachAsync(userHandlers, parallelOptions, async (uri, token) => “Take this array and naively fan out into parallel tasks and make a bunch of HTTP calls. You’ll be getting JSON back that is shaped like the GitHubUser.” We could make it even syntactically shorter if we used a record vs a class with this syntax: public record GitHubUser (string Name, string Bio); This makes “naïve” parallelism really easy. By naïve we mean “without inter-dependencies.” If you want to do something and you need to “fan out” this is super easy and clean. Sponsor: Make login Auth0’s problem. Not yours. Provide the convenient login features your customers want, like social login, multi-factor authentication, single sign-on, passwordless, and more. Get started for free. © 2021 Scott Hanselman. All rights reserved. Parallel.ForEachAsync in .NET 6 published first on http://7elementswd.tumblr.com/ via Tumblr Parallel.ForEachAsync in .NET 6
0 Comments
Leave a Reply. |
About UsIf you want to keep up with the latest in web design, you have to be willing to study and learn on an ongoing basis. If you are a web developer or web designer, you’ll find a lot of useful tutorials and code snippets collection here. Furthermore, we also discuss more general topics of web design and how the role of a web designer has evolved over the years.
|