Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

59 rindas
1.8 KiB

  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<MqttApplicationMessage> _messages = new List<MqttApplicationMessage>();
  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<MqttApplicationMessage>> LoadQueuedMessagesAsync()
  18. {
  19. var loadedMessages = await _storage.LoadQueuedMessagesAsync().ConfigureAwait(false);
  20. _messages.AddRange(loadedMessages);
  21. return _messages;
  22. }
  23. public async Task AddAsync(MqttApplicationMessage 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(MqttApplicationMessage 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. }