DBTaskQueue.cs 1006 B

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