DBQueryTask.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Threading.Tasks;
  3. using MongoDB.Driver;
  4. namespace Model
  5. {
  6. [ObjectSystem]
  7. public class DbQueryTaskSystem : ObjectSystem<DBQueryTask>, IAwake<string, TaskCompletionSource<Component>>
  8. {
  9. public void Awake(string collectionName, TaskCompletionSource<Component> tcs)
  10. {
  11. DBQueryTask self = this.Get();
  12. self.CollectionName = collectionName;
  13. self.Tcs = tcs;
  14. }
  15. }
  16. public sealed class DBQueryTask : DBTask
  17. {
  18. public string CollectionName { get; set; }
  19. public TaskCompletionSource<Component> Tcs { get; set; }
  20. public override async Task Run()
  21. {
  22. DBCacheComponent dbCacheComponent = Game.Scene.GetComponent<DBCacheComponent>();
  23. DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
  24. // 执行查询前先看看cache中是否已经存在
  25. Component disposer = dbCacheComponent.GetFromCache(this.CollectionName, this.Id);
  26. if (disposer != null)
  27. {
  28. this.Tcs.SetResult(disposer);
  29. return;
  30. }
  31. try
  32. {
  33. // 执行查询数据库任务
  34. disposer = await dbComponent.GetCollection(this.CollectionName).FindAsync((s) => s.Id == this.Id).Result.FirstOrDefaultAsync();
  35. if (disposer != null)
  36. {
  37. dbCacheComponent.AddToCache(disposer);
  38. }
  39. this.Tcs.SetResult(disposer);
  40. }
  41. catch (Exception e)
  42. {
  43. this.Tcs.SetException(new Exception($"查询数据库异常! {CollectionName} {Id}", e));
  44. }
  45. }
  46. }
  47. }