Created
March 4, 2021 07:33
-
-
Save maximgorbatyuk/ff402d446db28da5438ce44a31332896 to your computer and use it in GitHub Desktop.
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.Collections.Generic; | |
using System.Diagnostics; | |
using System.Linq; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace MultiThread_25 | |
{ | |
class Program | |
{ | |
private const int MaxCount = 100_000_000; | |
private static IEnumerable<int> Collection => Enumerable.Repeat(1, MaxCount); | |
static async Task Main(string[] args) | |
{ | |
GetSum("Обычное", (() => Collection.Sum(x => x))); | |
var portions = PreparePortions(); | |
await GetSum("Параллельное Task,", async () => | |
{ | |
var threads = new List<Task<int>>(); | |
for (var i = 0; i < portions.Count; i++) | |
{ | |
int index = i; | |
var thread = new Task<int>(() => | |
{ | |
return portions[index].Sum(x => x); | |
}); | |
threads.Add(thread); | |
thread.Start(); | |
} | |
return (await Task.WhenAll(threads)).Sum(); | |
}); | |
GetSum("Параллельное с помощью LINQ", (() => Collection.AsParallel().Sum())); | |
Console.ReadKey(); | |
} | |
private static IReadOnlyList<IEnumerable<int>> PreparePortions() | |
{ | |
var portions = new List<IEnumerable<int>>(); | |
const int partLength = MaxCount / 4; | |
for (int i = 0; i < 4; i++) | |
{ | |
portions.Add(Collection.Skip(i * partLength).Take(partLength)); | |
} | |
return portions; | |
} | |
private static void GetSum(string descr, Func<int> f) | |
{ | |
var stopwatch = new Stopwatch(); | |
stopwatch.Start(); | |
var result = f(); | |
stopwatch.Stop(); | |
Console.WriteLine($"{descr}: сумма = {result} to {stopwatch.ElapsedMilliseconds} мс."); | |
} | |
private static async Task GetSum(string descr, Func<Task<int>> f) | |
{ | |
var stopwatch = new Stopwatch(); | |
stopwatch.Start(); | |
var result = await f(); | |
stopwatch.Stop(); | |
Console.WriteLine($"{descr}: сумма = {result} to {stopwatch.ElapsedMilliseconds} мс."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment