DBSaveTask.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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(long id): base(id)
  23. {
  24. }
  25. public override async Task Run()
  26. {
  27. DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
  28. try
  29. {
  30. // 执行保存数据库任务
  31. await dbComponent.GetCollection(this.CollectionName).ReplaceOneAsync(s => s.Id == this.Entity.Id, this.Entity, new UpdateOptions {IsUpsert = true});
  32. this.Tcs.SetResult(true);
  33. }
  34. catch (Exception e)
  35. {
  36. this.Tcs.SetException(new Exception($"保存数据失败! {CollectionName} {Id}", e));
  37. }
  38. }
  39. }
  40. }