IDistributedLock.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using Microsoft.AspNetCore.DataProtection.KeyManagement;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using XF.Domain.Exceptions;
  8. namespace XF.Domain.Locks
  9. {
  10. public interface IDistributedLock
  11. {
  12. public bool Acquire(string key, TimeSpan expired);
  13. public Task<bool> AcquireAsync(string key, TimeSpan expired, CancellationToken cancellationToken);
  14. public void Release(string key);
  15. public Task ReleaseAsync(string key, CancellationToken cancellationToken);
  16. }
  17. public class LockManager : IDisposable
  18. {
  19. private readonly IDistributedLock _locker;
  20. private readonly string _key;
  21. public LockManager(IDistributedLock locker, string key)
  22. {
  23. _locker = locker;
  24. _key = key;
  25. }
  26. /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
  27. public void Dispose()
  28. {
  29. _locker.Release(_key);
  30. }
  31. public void InvokeInLock(Action doSome, TimeSpan expired)
  32. {
  33. if (_locker.Acquire(_key, expired))
  34. {
  35. try
  36. {
  37. doSome();
  38. }
  39. catch (Exception e)
  40. {
  41. Console.WriteLine(e);
  42. throw;
  43. }
  44. finally
  45. {
  46. _locker.Release(_key);
  47. }
  48. }
  49. else
  50. {
  51. throw new UserFriendlyException("系统忙,请稍后重试");
  52. }
  53. }
  54. public async Task InvokeInLockAsync(Func<CancellationToken, Task> doSome, TimeSpan expired, CancellationToken cancellationToken)
  55. {
  56. if (await _locker.AcquireAsync(_key, expired, cancellationToken))
  57. {
  58. try
  59. {
  60. await doSome(cancellationToken);
  61. }
  62. catch (Exception e)
  63. {
  64. Console.WriteLine(e);
  65. throw;
  66. }
  67. finally
  68. {
  69. await _locker.ReleaseAsync(_key, cancellationToken);
  70. }
  71. }
  72. else
  73. {
  74. throw new UserFriendlyException("系统忙,请稍后重试");
  75. }
  76. }
  77. }
  78. }