-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAsynchronousToSynchronous.cs
More file actions
53 lines (46 loc) · 1.77 KB
/
AsynchronousToSynchronous.cs
File metadata and controls
53 lines (46 loc) · 1.77 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
using System;
using System.Collections.Generic;
using System.Threading;
namespace AlgorithmsAndDataStructures.DataStructures.Concurrency;
public class AsynchronousToSynchronous
{
#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);
}
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();
});
}
}
}