DBSaveBatchTask.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Collections.Generic;
  3. using MongoDB.Bson;
  4. using MongoDB.Driver;
  5. namespace ETModel
  6. {
  7. [ObjectSystem]
  8. public class DbSaveBatchTaskSystem : AwakeSystem<DBSaveBatchTask, List<ComponentWithId>, string, ETTaskCompletionSource<bool>>
  9. {
  10. public override void Awake(DBSaveBatchTask self, List<ComponentWithId> components, string collectionName, ETTaskCompletionSource<bool> tcs)
  11. {
  12. self.Components = components;
  13. self.CollectionName = collectionName;
  14. self.Tcs = tcs;
  15. }
  16. }
  17. public sealed class DBSaveBatchTask : DBTask
  18. {
  19. public string CollectionName { get; set; }
  20. public List<ComponentWithId> Components;
  21. public ETTaskCompletionSource<bool> Tcs;
  22. public override async ETTask Run()
  23. {
  24. DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
  25. foreach (ComponentWithId component in this.Components)
  26. {
  27. if (component == null)
  28. {
  29. continue;
  30. }
  31. try
  32. {
  33. // 执行保存数据库任务
  34. await dbComponent.GetCollection(this.CollectionName).ReplaceOneAsync(s => s.Id == component.Id, component, new UpdateOptions { IsUpsert = true });
  35. }
  36. catch (Exception e)
  37. {
  38. Log.Debug($"{component.GetType().Name} {component.ToJson()} {e}");
  39. this.Tcs.SetException(new Exception($"保存数据失败! {CollectionName} {this.Components.ListToString()}", e));
  40. }
  41. }
  42. this.Tcs.SetResult(true);
  43. }
  44. }
  45. }