DBSaveTask.cs 1.1 KB

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