MultiSave.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using InABox.Clients;
  5. namespace InABox.Core
  6. {
  7. public class MultiSave
  8. {
  9. private readonly Dictionary<Type, List<Entity>> _updates = new Dictionary<Type, List<Entity>>();
  10. public void Clear()
  11. {
  12. _updates.Clear();
  13. }
  14. public void Add(Entity entity)
  15. {
  16. Add(entity.GetType(), entity);
  17. }
  18. public void Add(Type type, params Entity[] entities)
  19. {
  20. if (!_updates.ContainsKey(type))
  21. _updates[type] = new List<Entity>();
  22. _updates[type].AddRange(entities);
  23. }
  24. public void Save(Action<MultiSave>? callback = null, string audittrail = "")
  25. {
  26. var tasks = new List<Task>();
  27. foreach (var type in _updates.Keys)
  28. {
  29. var task = Task.Run(
  30. () =>
  31. {
  32. var client = ClientFactory.CreateClient(type);
  33. client.Save(_updates[type], audittrail);
  34. }
  35. );
  36. tasks.Add(task);
  37. }
  38. if (callback != null)
  39. Task.WhenAll(tasks.ToArray()).ContinueWith(t => { callback.Invoke(this); });
  40. else
  41. Task.WaitAll(tasks.ToArray());
  42. }
  43. }
  44. }