DBQueryTask.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Threading.Tasks;
  3. using MongoDB.Driver;
  4. namespace Model
  5. {
  6. [ObjectEvent]
  7. public class DBQueryTaskEvent : ObjectEvent<DBQueryTask>, IAwake<string, TaskCompletionSource<Disposer>>
  8. {
  9. public void Awake(string collectionName, TaskCompletionSource<Disposer> 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<Disposer> Tcs { get; set; }
  20. public DBQueryTask(long id): base(id)
  21. {
  22. }
  23. public override async Task Run()
  24. {
  25. DBCacheComponent dbCacheComponent = Game.Scene.GetComponent<DBCacheComponent>();
  26. DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
  27. // 执行查询前先看看cache中是否已经存在
  28. Disposer disposer = dbCacheComponent.GetFromCache(this.CollectionName, this.Id);
  29. if (disposer != null)
  30. {
  31. this.Tcs.SetResult(disposer);
  32. return;
  33. }
  34. try
  35. {
  36. // 执行查询数据库任务
  37. disposer = await dbComponent.GetCollection(this.CollectionName).FindAsync((s) => s.Id == this.Id).Result.FirstOrDefaultAsync();
  38. if (disposer != null)
  39. {
  40. dbCacheComponent.AddToCache(disposer);
  41. }
  42. this.Tcs.SetResult(disposer);
  43. }
  44. catch (Exception e)
  45. {
  46. this.Tcs.SetException(new Exception($"查询数据库异常! {CollectionName} {Id}", e));
  47. }
  48. }
  49. }
  50. }