-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathProgram.cs
64 lines (55 loc) · 1.77 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
// Bulkhead pattern
// https://learn.microsoft.com/en-us/azure/architecture/patterns/bulkhead
using System.Collections.Concurrent;
namespace DesignPatterns.Bulkhead;
class Program
{
static readonly int MaxParallelTasks = 3; // Maximum number of concurrent tasks
static readonly int MaxQueueSize = 5; // Maximum number of tasks in the queue
static readonly SemaphoreSlim _semaphore = new(MaxParallelTasks);
static readonly ConcurrentQueue<Func<Task>> _taskQueue = new();
static async Task Main(string[] args)
{
var tasks = new Task[100];
for (int i = 0; i < 100; i++)
{
int taskId = i;
tasks[i] = EnqueueTask(async () =>
{
Console.WriteLine($"Task {taskId} started. Thread ID: {Thread.CurrentThread.ManagedThreadId}");
await Task.Delay(2000); // Simulating processing time
Console.WriteLine($"Task {taskId} completed.");
});
}
await Task.WhenAll(tasks);
Console.WriteLine("All tasks completed.");
}
private static async Task EnqueueTask(Func<Task> task)
{
if (_taskQueue.Count >= MaxQueueSize)
{
Console.WriteLine("Task rejected! Bulkhead capacity is full.");
return;
}
_taskQueue.Enqueue(task);
await ProcessQueue();
}
private static async Task ProcessQueue()
{
while (_taskQueue.TryDequeue(out var task))
{
await _semaphore.WaitAsync();
_ = Task.Run(async () =>
{
try
{
await task();
}
finally
{
_semaphore.Release();
}
});
}
}
}