DBQueryJsonTask.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using MongoDB.Driver;
  5. namespace Model
  6. {
  7. [ObjectEvent]
  8. public class DBQueryJsonTaskEvent : ObjectEvent<DBQueryJsonTask>, IAwake<string, string, TaskCompletionSource<List<Entity>>>
  9. {
  10. public void Awake(string collectionName, string json, TaskCompletionSource<List<Entity>> tcs)
  11. {
  12. DBQueryJsonTask self = this.Get();
  13. self.CollectionName = collectionName;
  14. self.Json = json;
  15. self.Tcs = tcs;
  16. }
  17. }
  18. public sealed class DBQueryJsonTask : DBTask
  19. {
  20. public string CollectionName { get; set; }
  21. public string Json { get; set; }
  22. public TaskCompletionSource<List<Entity>> Tcs { get; set; }
  23. public override async Task Run()
  24. {
  25. DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
  26. try
  27. {
  28. // 执行查询数据库任务
  29. FilterDefinition<Entity> filterDefinition = new JsonFilterDefinition<Entity>(this.Json);
  30. List<Entity> entitys = await dbComponent.GetCollection(this.CollectionName).FindAsync(filterDefinition).Result.ToListAsync();
  31. this.Tcs.SetResult(entitys);
  32. }
  33. catch (Exception e)
  34. {
  35. this.Tcs.SetException(new Exception($"查询数据库异常! {CollectionName} {this.Json}", e));
  36. }
  37. }
  38. }
  39. }