Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

63 lignes
2.1 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<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. if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));
  26. using (await _messagesLock.LockAsync(CancellationToken.None).ConfigureAwait(false))
  27. {
  28. _messages.Add(applicationMessage);
  29. await SaveAsync().ConfigureAwait(false);
  30. }
  31. }
  32. public async Task RemoveAsync(ManagedMqttApplicationMessage applicationMessage)
  33. {
  34. if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));
  35. using (await _messagesLock.LockAsync(CancellationToken.None).ConfigureAwait(false))
  36. {
  37. var index = _messages.IndexOf(applicationMessage);
  38. if (index == -1)
  39. {
  40. return;
  41. }
  42. _messages.RemoveAt(index);
  43. await SaveAsync().ConfigureAwait(false);
  44. }
  45. }
  46. private Task SaveAsync()
  47. {
  48. return _storage.SaveQueuedMessagesAsync(_messages);
  49. }
  50. }
  51. }