DBSaveBatchTask.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 DbSaveBatchTaskSystem : AwakeSystem<DBSaveBatchTask, List<Component>, string, TaskCompletionSource<bool>>
  10. {
  11. public override void Awake(DBSaveBatchTask self, List<Component> components, string collectionName, TaskCompletionSource<bool> tcs)
  12. {
  13. self.Components = components;
  14. self.CollectionName = collectionName;
  15. self.Tcs = tcs;
  16. }
  17. }
  18. public sealed class DBSaveBatchTask : DBTask
  19. {
  20. public string CollectionName { get; set; }
  21. public List<Component> Components;
  22. public TaskCompletionSource<bool> Tcs;
  23. public override async Task Run()
  24. {
  25. DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
  26. foreach (Component component in this.Components)
  27. {
  28. if (component == null)
  29. {
  30. continue;
  31. }
  32. try
  33. {
  34. // 执行保存数据库任务
  35. await dbComponent.GetCollection(this.CollectionName).ReplaceOneAsync(s => s.Id == component.Id, component, new UpdateOptions { IsUpsert = true });
  36. }
  37. catch (Exception e)
  38. {
  39. Log.Debug($"{component.GetType().Name} {component.ToJson()} {e}");
  40. this.Tcs.SetException(new Exception($"保存数据失败! {CollectionName} {this.Components.ListToString()}", e));
  41. }
  42. }
  43. this.Tcs.SetResult(true);
  44. }
  45. }
  46. }