-
Notifications
You must be signed in to change notification settings - Fork 1
/
AsynchronousToSynchronous.cs
60 lines (54 loc) · 1.98 KB
/
AsynchronousToSynchronous.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
using System;
using System.Collections.Generic;
using System.Threading;
namespace AlgorithmsAndDataStructures.DataStructures.Concurrency
{
public class AsynchronousToSynchronous
{
private class AsyncExecutor
{
#pragma warning disable HAA0302 // Display class allocation to capture closure
#pragma warning disable CA1822 // Mark members as static
public void ExecuteAsync(Action callback)
#pragma warning restore CA1822 // Mark members as static
#pragma warning restore HAA0302 // Display class allocation to capture closure
{
if (callback is null)
{
return;
}
#pragma warning disable HAA0301 // Closure Allocation Source
_ = ThreadPool.QueueUserWorkItem(_ =>
#pragma warning restore HAA0301 // Closure Allocation Source
{
Thread.Sleep(1);
callback();
});
}
}
#pragma warning disable CA1822 // Mark members as static
#pragma warning disable HAA0302 // Display class allocation to capture closure
public void ExecuteSync(Queue<int> queue)
#pragma warning restore HAA0302 // Display class allocation to capture closure
#pragma warning restore CA1822 // Mark members as static
{
if (queue is null)
{
return;
}
var asyncExecutor = new AsyncExecutor();
#pragma warning disable HAA0302 // Display class allocation to capture closure
using var resetEvent = new AutoResetEvent(false);
#pragma warning restore HAA0302 // Display class allocation to capture closure
#pragma warning disable HAA0301 // Closure Allocation Source
asyncExecutor.ExecuteAsync(() =>
#pragma warning restore HAA0301 // Closure Allocation Source
{
queue.Enqueue(1);
resetEvent.Set();
});
resetEvent.WaitOne();
queue.Enqueue(2);
}
}
}