DBQueryBatchTask.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using MongoDB.Bson;
  5. using MongoDB.Driver;
  6. namespace ETModel
  7. {
  8. [ObjectSystem]
  9. public class DbQueryBatchTaskSystem : AwakeSystem<DBQueryBatchTask, List<long>, string, TaskCompletionSource<List<ComponentWithId>>>
  10. {
  11. public override void Awake(DBQueryBatchTask self, List<long> idList, string collectionName, TaskCompletionSource<List<ComponentWithId>> tcs)
  12. {
  13. self.IdList = idList;
  14. self.CollectionName = collectionName;
  15. self.Tcs = tcs;
  16. }
  17. }
  18. public sealed class DBQueryBatchTask : DBTask
  19. {
  20. public string CollectionName { get; set; }
  21. public List<long> IdList { get; set; }
  22. public TaskCompletionSource<List<ComponentWithId>> Tcs { get; set; }
  23. public override async Task Run()
  24. {
  25. DBCacheComponent dbCacheComponent = Game.Scene.GetComponent<DBCacheComponent>();
  26. DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
  27. List<ComponentWithId> result = new List<ComponentWithId>();
  28. try
  29. {
  30. // 执行查询数据库任务
  31. foreach (long id in IdList)
  32. {
  33. ComponentWithId component = dbCacheComponent.GetFromCache(this.CollectionName, id);
  34. if (component == null)
  35. {
  36. component = await dbComponent.GetCollection(this.CollectionName).FindAsync((s) => s.Id == id).Result.FirstOrDefaultAsync();
  37. }
  38. if (component == null)
  39. {
  40. continue;
  41. }
  42. result.Add(component);
  43. }
  44. this.Tcs.SetResult(result);
  45. }
  46. catch (Exception e)
  47. {
  48. this.Tcs.SetException(new Exception($"查询数据库异常! {this.CollectionName} {IdList.ListToString()}", e));
  49. }
  50. }
  51. }
  52. }