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