Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

ManagedMqttClientStorageManager.cs 1.9 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using MQTTnet.Internal;
  6. namespace MQTTnet.Extensions.ManagedClient
  7. {
  8. public class ManagedMqttClientStorageManager
  9. {
  10. private readonly List<ManagedMqttApplicationMessage> _messages = new List<ManagedMqttApplicationMessage>();
  11. private readonly AsyncLock _messagesLock = new AsyncLock();
  12. private readonly IManagedMqttClientStorage _storage;
  13. public ManagedMqttClientStorageManager(IManagedMqttClientStorage storage)
  14. {
  15. _storage = storage ?? throw new ArgumentNullException(nameof(storage));
  16. }
  17. public async Task<List<ManagedMqttApplicationMessage>> LoadQueuedMessagesAsync()
  18. {
  19. var loadedMessages = await _storage.LoadQueuedMessagesAsync().ConfigureAwait(false);
  20. _messages.AddRange(loadedMessages);
  21. return _messages;
  22. }
  23. public async Task AddAsync(ManagedMqttApplicationMessage applicationMessage)
  24. {
  25. using (await _messagesLock.LockAsync(CancellationToken.None).ConfigureAwait(false))
  26. {
  27. _messages.Add(applicationMessage);
  28. await SaveAsync().ConfigureAwait(false);
  29. }
  30. }
  31. public async Task RemoveAsync(ManagedMqttApplicationMessage applicationMessage)
  32. {
  33. using (await _messagesLock.LockAsync(CancellationToken.None).ConfigureAwait(false))
  34. {
  35. var index = _messages.IndexOf(applicationMessage);
  36. if (index == -1)
  37. {
  38. return;
  39. }
  40. _messages.RemoveAt(index);
  41. await SaveAsync().ConfigureAwait(false);
  42. }
  43. }
  44. private Task SaveAsync()
  45. {
  46. return _storage.SaveQueuedMessagesAsync(_messages);
  47. }
  48. }
  49. }