From 69ee28395093f0da6a1742d36e1774eaf0ba4db4 Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Fri, 14 Oct 2022 14:48:04 +0200 Subject: [PATCH] Add `TaskQueue` class --- Stone_Red-C-Sharp-Utilities/TaskQueue.cs | 59 ++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Stone_Red-C-Sharp-Utilities/TaskQueue.cs diff --git a/Stone_Red-C-Sharp-Utilities/TaskQueue.cs b/Stone_Red-C-Sharp-Utilities/TaskQueue.cs new file mode 100644 index 0000000..fba3276 --- /dev/null +++ b/Stone_Red-C-Sharp-Utilities/TaskQueue.cs @@ -0,0 +1,59 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Stone_Red_C_Sharp_Utilities +{ + /// + /// An queue. + /// + public class TaskQueue + { + private readonly SemaphoreSlim semaphore; + + /// + /// Creates a new + /// + public TaskQueue() + { + semaphore = new SemaphoreSlim(1); + } + + /// + /// Enqueues a . + /// + /// The return type. + /// The code to enqueue. + /// A to await + public async Task Enqueue(Func function) + { + await semaphore.WaitAsync(); + try + { + return await Task.Run(function); + } + finally + { + _ = semaphore.Release(); + } + } + + /// + /// Enqueues an . + /// + /// The code to enqueue. + /// A to await + public async Task Enqueue(Action function) + { + await semaphore.WaitAsync(); + try + { + await Task.Run(function); + } + finally + { + _ = semaphore.Release(); + } + } + } +} \ No newline at end of file