MultiSave.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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(Type type, params Entity[] entities)
  15. {
  16. if (!_updates.ContainsKey(type))
  17. _updates[type] = new List<Entity>();
  18. _updates[type].AddRange(entities);
  19. }
  20. public void Save(Action<MultiSave>? callback = null, string audittrail = "")
  21. {
  22. var tasks = new List<Task>();
  23. foreach (var type in _updates.Keys)
  24. {
  25. var task = Task.Run(
  26. () =>
  27. {
  28. var client = ClientFactory.CreateClient(type);
  29. client.Save(_updates[type], audittrail);
  30. }
  31. );
  32. tasks.Add(task);
  33. }
  34. if (callback != null)
  35. Task.WhenAll(tasks.ToArray()).ContinueWith(t => { callback.Invoke(this); });
  36. else
  37. Task.WaitAll(tasks.ToArray());
  38. }
  39. }
  40. }