DBTaskQueue.cs 957 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. namespace Model
  5. {
  6. public sealed class DBTaskQueue : Entity
  7. {
  8. public Queue<DBTask> queue = new Queue<DBTask>();
  9. private TaskCompletionSource<DBTask> tcs;
  10. public async void Start()
  11. {
  12. while (true)
  13. {
  14. if (this.Id == 0)
  15. {
  16. return;
  17. }
  18. DBTask task = await this.Get();
  19. try
  20. {
  21. await task.Run();
  22. }
  23. catch (Exception e)
  24. {
  25. Log.Error(e.ToString());
  26. }
  27. }
  28. }
  29. public void Add(DBTask task)
  30. {
  31. if (this.tcs != null)
  32. {
  33. var t = this.tcs;
  34. this.tcs = null;
  35. t.SetResult(task);
  36. return;
  37. }
  38. this.queue.Enqueue(task);
  39. }
  40. public Task<DBTask> Get()
  41. {
  42. TaskCompletionSource<DBTask> t = new TaskCompletionSource<DBTask>();
  43. if (this.queue.Count > 0)
  44. {
  45. DBTask task = this.queue.Dequeue();
  46. t.SetResult(task);
  47. }
  48. else
  49. {
  50. this.tcs = t;
  51. }
  52. return t.Task;
  53. }
  54. }
  55. }