|
| 1 | +using System; |
| 2 | +using System.Collections.Concurrent; |
| 3 | +using System.IO.Pipelines; |
| 4 | +using System.Threading; |
| 5 | + |
| 6 | +namespace GenHTTP.Engine.Infrastructure.Transport |
| 7 | +{ |
| 8 | + |
| 9 | + internal sealed class IOQueue : PipeScheduler, IThreadPoolWorkItem |
| 10 | + { |
| 11 | + private readonly ConcurrentQueue<Work> _workItems = new(); |
| 12 | + |
| 13 | + private int _doingWork; |
| 14 | + |
| 15 | + public override void Schedule(Action<object?> action, object? state) |
| 16 | + { |
| 17 | + _workItems.Enqueue(new Work(action, state)); |
| 18 | + |
| 19 | + // Set working if it wasn't (via atomic Interlocked). |
| 20 | + if (Interlocked.CompareExchange(ref _doingWork, 1, 0) == 0) |
| 21 | + { |
| 22 | + // Wasn't working, schedule. |
| 23 | + System.Threading.ThreadPool.UnsafeQueueUserWorkItem(this, preferLocal: false); |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + void IThreadPoolWorkItem.Execute() |
| 28 | + { |
| 29 | + while (true) |
| 30 | + { |
| 31 | + while (_workItems.TryDequeue(out Work item)) |
| 32 | + { |
| 33 | + item.Callback(item.State); |
| 34 | + } |
| 35 | + |
| 36 | + // All work done. |
| 37 | + |
| 38 | + // Set _doingWork (0 == false) prior to checking IsEmpty to catch any missed work in interim. |
| 39 | + // This doesn't need to be volatile due to the following barrier (i.e. it is volatile). |
| 40 | + _doingWork = 0; |
| 41 | + |
| 42 | + // Ensure _doingWork is written before IsEmpty is read. |
| 43 | + // As they are two different memory locations, we insert a barrier to guarantee ordering. |
| 44 | + Thread.MemoryBarrier(); |
| 45 | + |
| 46 | + // Check if there is work to do |
| 47 | + if (_workItems.IsEmpty) |
| 48 | + { |
| 49 | + // Nothing to do, exit. |
| 50 | + break; |
| 51 | + } |
| 52 | + |
| 53 | + // Is work, can we set it as active again (via atomic Interlocked), prior to scheduling? |
| 54 | + if (Interlocked.Exchange(ref _doingWork, 1) == 1) |
| 55 | + { |
| 56 | + // Execute has been rescheduled already, exit. |
| 57 | + break; |
| 58 | + } |
| 59 | + |
| 60 | + // Is work, wasn't already scheduled so continue loop. |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + private readonly struct Work |
| 65 | + { |
| 66 | + public readonly Action<object?> Callback; |
| 67 | + |
| 68 | + public readonly object? State; |
| 69 | + |
| 70 | + public Work(Action<object?> callback, object? state) |
| 71 | + { |
| 72 | + Callback = callback; |
| 73 | + State = state; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + } |
| 78 | + |
| 79 | +} |
0 commit comments