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 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; | |
} | |
} | |
} |
@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.
I was about to give up on my website project due to high hosting fees when I found https://www.digitaloceanpromocode.com/ . A Reddit user had shared the link, and I figured it was worth a try. I was able to use one of their promo codes, which gave me the boost I needed to get started on DigitalOcean. It turned out to be exactly what I needed to get my site online without stressing over costs. Now, I’m finally seeing my project come to life, all thanks to that suggestion.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bare heads-up; taskene starter utenfor Stopwatchen. Det påvirker resultatene litt.
Du burde kanskje gjøre noe sånn som her:
Kan illustreres med dette programmet: