-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathParallelTasksProgram.cs
More file actions
68 lines (51 loc) · 2.07 KB
/
Copy pathParallelTasksProgram.cs
File metadata and controls
68 lines (51 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System.Diagnostics;
namespace Otus.AsyncAwait
{
public class ParallelTasksProgram
{
public async Task Execute1Async() {
var stopwatch = new Stopwatch();
stopwatch.Start();
var list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };
foreach (var item in list)
{
await SomeLongAwaitingAsync(item);
}
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
}
public async Task Execute2Async() {
var stopwatch = new Stopwatch();
stopwatch.Start();
var list = new List<int>() { 2, 1, 3, 4, 5, 6, 7, 8, 9, 10, };
List<Task<int>> tasks = new List<Task<int>>();
foreach (var item in list)
{
tasks.Add(SomeLongAwaitingAsync(item));
}
await Task.WhenAll(tasks);
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
}
public async Task Execute3Async() {
var stopwatch = new Stopwatch();
stopwatch.Start();
var list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };
await Parallel.ForEachAsync(list, async (item, cancellationToken) =>
{
await SomeLongAwaitingAsync(item);
});
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
}
private async Task<int> SomeLongAwaitingAsync(int item)
{
int timeOnOperationMs = new Random().Next(1000, 3000);
Console.WriteLine($"start delay for {item} thread № {Environment.CurrentManagedThreadId}");
await Task.Delay(TimeSpan.FromMilliseconds(timeOnOperationMs));
Console.WriteLine($"finish delay for {item} thread {Environment.CurrentManagedThreadId}");
//Console.WriteLine($"finish delay for {item} thread № {Environment.CurrentManagedThreadId}");
return await Task.FromResult(item);
}
}
}