TaskQueue.cs 684 B

12345678910111213141516171819202122232425262728
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace S7.Net.Internal
  5. {
  6. internal class TaskQueue
  7. {
  8. private static readonly object Sentinel = new object();
  9. private Task prev = Task.FromResult(Sentinel);
  10. public async Task<T> Enqueue<T>(Func<Task<T>> action)
  11. {
  12. var tcs = new TaskCompletionSource<object>();
  13. await Interlocked.Exchange(ref prev, tcs.Task).ConfigureAwait(false);
  14. try
  15. {
  16. return await action.Invoke().ConfigureAwait(false);
  17. }
  18. finally
  19. {
  20. tcs.SetResult(Sentinel);
  21. }
  22. }
  23. }
  24. }