Compile with:
csc /r:System.Net.Http.dll app.cs
and run App.exe.
Comparing the use of foreach loop without lambdas and the use of a pipeline
(such as ....Select(...).Aggregate(...)) with lambdas and the resulting
sequential versus concurrent behavior.
static async Task<int> FetchAndSum(string[] urls) {
int sum = 0;
using(HttpClient httpClient = new HttpClient()) {
foreach(var url in urls) {
Console.WriteLine($"FETCHING from {url}");
var body = await httpClient.GetStringAsync(url);
Console.WriteLine($"=======> from {url}");
sum += body.Length;
}
}
return sum;
} |
static async Task<int> FetchAndSumλ(string[] urls) {
using(HttpClient httpClient = new HttpClient()) {
return await urls
.Select(async url => {
Console.WriteLine($"FETCHING from {url}");
var body = await httpClient.GetStringAsync(url);
Console.WriteLine($"=======> from {url}");
return body.Length;
})
.Aggregate(async (prev, curr) => await prev + await curr);
}
} |
|
|