-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
127 lines (107 loc) · 3.84 KB
/
Program.cs
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
namespace Test;
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
static class Program
{
static async Task<DBNull> DoSomething()
{
await Task.Yield();
return DBNull.Value;
}
static async Task<DBNull?> TestWithAsyncStateMachine()
{
try
{
return await DoSomething();
}
catch
{
return null;
}
}
static Task<DBNull?> TestWithoutAsyncStateMachine()
{
return DoSomething().ContinueWith(
t => t.IsCompletedSuccessfully ? t.GetAwaiter().GetResult() : null,
cancellationToken: default,
continuationOptions: TaskContinuationOptions.ExecuteSynchronously,
scheduler: TaskScheduler.Default);
}
static async Task<long> Test(Func<Task<DBNull?>> tester, int count)
{
var sw = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
{
await tester();
}
return sw.ElapsedMilliseconds;
}
static async Task RunTest(
Func<Func<Task<long>>, Task<long>> runner,
int count)
{
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true);
var withoutAsync = await runner(() => Test(TestWithoutAsyncStateMachine, count));
Console.WriteLine($"{nameof(TestWithoutAsyncStateMachine)}: {withoutAsync}ms");
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true);
var withAsync = await runner(() => Test(TestWithAsyncStateMachine, count));
Console.WriteLine($"{nameof(TestWithAsyncStateMachine)}: {withAsync}ms");
}
static async Task Main()
{
const int threads = 1000;
const int iterations = 10000000;
ThreadPool.SetMinThreads(threads, threads);
ThreadPool.SetMaxThreads(threads, threads);
var pump = new PumpingSyncContext();
Console.WriteLine($"Testing with {nameof(PumpingSyncContext)}...");
await RunTest(func => pump.Run(func), iterations);
Console.WriteLine($"Testing with {nameof(Task.Run)}...");
await RunTest(func => Task.Run(func), iterations);
await pump.Complete();
Console.WriteLine("Ended");
}
}
/// <summary>
/// Test async calls on single thread for more deterministic results
/// </summary>
public class PumpingSyncContext : SynchronizationContext
{
private readonly BlockingCollection<(SendOrPostCallback, object?)> _workItems = new();
private readonly Task _threadTask;
private readonly TaskScheduler _taskScheduler;
public PumpingSyncContext()
{
var tcs = new TaskCompletionSource<TaskScheduler>();
_threadTask = Task.Factory.StartNew(() =>
{
SetSynchronizationContext(this);
try
{
tcs.SetResult(TaskScheduler.FromCurrentSynchronizationContext());
foreach (var (callback, arg) in _workItems.GetConsumingEnumerable())
callback(arg);
}
finally
{
SetSynchronizationContext(null);
}
}, TaskCreationOptions.LongRunning);
_taskScheduler = tcs.Task.GetAwaiter().GetResult();
}
public Task Complete()
{
_workItems.CompleteAdding();
return _threadTask;
}
public override void Post(SendOrPostCallback d, object? state) =>
_workItems.Add((d, state));
public override void Send(SendOrPostCallback d, object? state) =>
throw new NotImplementedException(nameof(Send));
public override SynchronizationContext CreateCopy() => this;
public Task<T> Run<T>(Func<Task<T>> func, CancellationToken cancellationToken = default) =>
Task.Factory.StartNew(func, cancellationToken, creationOptions: default, _taskScheduler).Unwrap();
}