DBSaveBatchTask.cs 1.3 KB

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