You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

76 lines
2.0 KiB

  1. using System.Collections.Generic;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace MQTTnet.Core.ManagedClient
  5. {
  6. public class ManagedMqttClientStorageManager
  7. {
  8. private readonly List<MqttApplicationMessage> _applicationMessages = new List<MqttApplicationMessage>();
  9. private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
  10. private IManagedMqttClientStorage _storage;
  11. public async Task SetStorageAsync(IManagedMqttClientStorage storage)
  12. {
  13. await _semaphore.WaitAsync().ConfigureAwait(false);
  14. try
  15. {
  16. _storage = storage;
  17. }
  18. finally
  19. {
  20. _semaphore.Release();
  21. }
  22. }
  23. public async Task AddAsync(MqttApplicationMessage applicationMessage)
  24. {
  25. await _semaphore.WaitAsync().ConfigureAwait(false);
  26. try
  27. {
  28. if (_storage == null)
  29. {
  30. return;
  31. }
  32. _applicationMessages.Add(applicationMessage);
  33. await SaveAsync().ConfigureAwait(false);
  34. }
  35. finally
  36. {
  37. _semaphore.Release();
  38. }
  39. }
  40. public async Task RemoveAsync(MqttApplicationMessage applicationMessage)
  41. {
  42. await _semaphore.WaitAsync().ConfigureAwait(false);
  43. try
  44. {
  45. if (_storage == null)
  46. {
  47. return;
  48. }
  49. var index = _applicationMessages.IndexOf(applicationMessage);
  50. if (index == -1)
  51. {
  52. return;
  53. }
  54. _applicationMessages.RemoveAt(index);
  55. await SaveAsync().ConfigureAwait(false);
  56. }
  57. finally
  58. {
  59. _semaphore.Release();
  60. }
  61. }
  62. private Task SaveAsync()
  63. {
  64. return _storage.SaveQueuedMessagesAsync(_applicationMessages);
  65. }
  66. }
  67. }