Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 

67 рядки
2.3 KiB

  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MQTTnet.Internal;
  9. namespace MQTTnet.Extensions.ManagedClient
  10. {
  11. public class ManagedMqttClientStorageManager
  12. {
  13. private readonly List<ManagedMqttApplicationMessage> _messages = new List<ManagedMqttApplicationMessage>();
  14. private readonly AsyncLock _messagesLock = new AsyncLock();
  15. private readonly IManagedMqttClientStorage _storage;
  16. public ManagedMqttClientStorageManager(IManagedMqttClientStorage storage)
  17. {
  18. _storage = storage ?? throw new ArgumentNullException(nameof(storage));
  19. }
  20. public async Task<List<ManagedMqttApplicationMessage>> LoadQueuedMessagesAsync()
  21. {
  22. var loadedMessages = await _storage.LoadQueuedMessagesAsync().ConfigureAwait(false);
  23. _messages.AddRange(loadedMessages);
  24. return _messages;
  25. }
  26. public async Task AddAsync(ManagedMqttApplicationMessage applicationMessage)
  27. {
  28. if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));
  29. using (await _messagesLock.WaitAsync(CancellationToken.None).ConfigureAwait(false))
  30. {
  31. _messages.Add(applicationMessage);
  32. await SaveAsync().ConfigureAwait(false);
  33. }
  34. }
  35. public async Task RemoveAsync(ManagedMqttApplicationMessage applicationMessage)
  36. {
  37. if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));
  38. using (await _messagesLock.WaitAsync(CancellationToken.None).ConfigureAwait(false))
  39. {
  40. var index = _messages.IndexOf(applicationMessage);
  41. if (index == -1)
  42. {
  43. return;
  44. }
  45. _messages.RemoveAt(index);
  46. await SaveAsync().ConfigureAwait(false);
  47. }
  48. }
  49. private Task SaveAsync()
  50. {
  51. return _storage.SaveQueuedMessagesAsync(_messages);
  52. }
  53. }
  54. }