DBTaskQueue.cs 925 B

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