Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

ManagedMqttClientStorageManager.cs 2.0 KiB

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