DBQueryBatchTask.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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, ETTaskCompletionSource<List<ComponentWithId>>>
  10. {
  11. public override void Awake(DBQueryBatchTask self, List<long> idList, string collectionName, ETTaskCompletionSource<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 ETTaskCompletionSource<List<ComponentWithId>> Tcs { get; set; }
  23. public override async ETTask 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. IAsyncCursor<ComponentWithId> cursor = await dbComponent.GetCollection(this.CollectionName).FindAsync((s) => s.Id == id);
  37. component = await cursor.FirstOrDefaultAsync();
  38. }
  39. if (component == null)
  40. {
  41. continue;
  42. }
  43. result.Add(component);
  44. }
  45. this.Tcs.SetResult(result);
  46. }
  47. catch (Exception e)
  48. {
  49. this.Tcs.SetException(new Exception($"查询数据库异常! {this.CollectionName} {IdList.ListToString()}", e));
  50. }
  51. }
  52. }
  53. }