Skip to content

Instantly share code, notes, and snippets.

@mastoj
Last active May 21, 2020 18:35
Show Gist options
  • Save mastoj/63dca564a928b9cba890049eae01bf54 to your computer and use it in GitHub Desktop.
Save mastoj/63dca564a928b9cba890049eae01bf54 to your computer and use it in GitHub Desktop.
Some plinq examples
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;
}
}
}
@mastoj
Copy link
Author

mastoj commented May 21, 2020

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment