DBSaveTask.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Threading.Tasks;
  3. using MongoDB.Driver;
  4. namespace Model
  5. {
  6. [ObjectEvent]
  7. public class DbSaveTaskSystem : ObjectSystem<DBSaveTask>, IAwake<Disposer, string, TaskCompletionSource<bool>>
  8. {
  9. public void Awake(Disposer entity, string collectionName, TaskCompletionSource<bool> tcs)
  10. {
  11. DBSaveTask self = this.Get();
  12. self.Disposer = entity;
  13. self.CollectionName = collectionName;
  14. self.Tcs = tcs;
  15. }
  16. }
  17. public sealed class DBSaveTask : DBTask
  18. {
  19. public Disposer Disposer;
  20. public string CollectionName { get; set; }
  21. public TaskCompletionSource<bool> Tcs;
  22. public override async Task Run()
  23. {
  24. DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
  25. try
  26. {
  27. // 执行保存数据库任务
  28. await dbComponent.GetCollection(this.CollectionName).ReplaceOneAsync(s => s.Id == this.Disposer.Id, this.Disposer, new UpdateOptions {IsUpsert = true});
  29. this.Tcs.SetResult(true);
  30. }
  31. catch (Exception e)
  32. {
  33. this.Tcs.SetException(new Exception($"保存数据失败! {CollectionName} {Id}", e));
  34. }
  35. }
  36. }
  37. }