DBQueryBatchTask.cs 1.6 KB

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