Last active
October 10, 2024 21:40
-
-
Save mastoj/63dca564a928b9cba890049eae01bf54 to your computer and use it in GitHub Desktop.
Some plinq examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Linq; | |
using System.Threading.Tasks; | |
namespace ParallelTest | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
RunTests(); | |
Console.ReadLine(); | |
} | |
private static async void RunTests() | |
{ | |
await Test(ToListExample, "ToListExample"); | |
await Test(NoToListExample, "NoToListExample"); | |
await Test(NoParallelExample, "NoParallelExample"); | |
} | |
private static async Task<int> NoParallelExample() | |
{ | |
var result = | |
await Task.WhenAll(Enumerable | |
.Range(0, 100) | |
.Select((_, index) => WorkWorkWork(index))); | |
var sum = result.Sum(); | |
return sum; | |
} | |
private static async Task<int> ToListExample() | |
{ | |
var result = | |
await Task.WhenAll(Enumerable | |
.Range(0, 100) | |
.AsParallel() | |
.Select((_, index) => WorkWorkWork(index)) | |
.ToList()); | |
var sum = result.Sum(); | |
return sum; | |
} | |
private static async Task<int> NoToListExample() | |
{ | |
var result = | |
await Task.WhenAll(Enumerable | |
.Range(0, 100) | |
.AsParallel() | |
.Select((_, index) => WorkWorkWork(index))); | |
var sum = result.Sum(); | |
return sum; | |
} | |
private static async Task Test(Func<Task<int>> target, string sampleTest) | |
{ | |
var sw = new Stopwatch(); | |
sw.Start(); | |
var sum = await target(); | |
Console.WriteLine($"Sum: {sum}"); | |
sw.Stop(); | |
Console.WriteLine($"{sampleTest} took {sw.ElapsedMilliseconds} ms"); | |
} | |
private static async Task<int> WorkWorkWork(int i) | |
{ | |
await Task.Delay(1000); | |
return i; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@kahole, you're completely right so I updated the sample. I'm more used to F# way of dealing with async, which doesn't stark the execution until you actually ask for the result.