NamedLock.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. namespace MediaBrowser.Common.Extensions
  6. {
  7. /// <summary>
  8. /// Class NamedLock
  9. /// </summary>
  10. public class NamedLock : IDisposable
  11. {
  12. /// <summary>
  13. /// The _locks
  14. /// </summary>
  15. private readonly Dictionary<string, SemaphoreSlim> _locks = new Dictionary<string, SemaphoreSlim>();
  16. /// <summary>
  17. /// Waits the async.
  18. /// </summary>
  19. /// <param name="name">The name.</param>
  20. /// <returns>Task.</returns>
  21. public Task WaitAsync(string name)
  22. {
  23. return GetLock(name).WaitAsync();
  24. }
  25. /// <summary>
  26. /// Releases the specified name.
  27. /// </summary>
  28. /// <param name="name">The name.</param>
  29. public void Release(string name)
  30. {
  31. SemaphoreSlim semaphore;
  32. if (_locks.TryGetValue(name, out semaphore))
  33. {
  34. semaphore.Release();
  35. }
  36. }
  37. /// <summary>
  38. /// Gets the lock.
  39. /// </summary>
  40. /// <param name="filename">The filename.</param>
  41. /// <returns>System.Object.</returns>
  42. private SemaphoreSlim GetLock(string filename)
  43. {
  44. SemaphoreSlim fileLock;
  45. lock (_locks)
  46. {
  47. if (!_locks.TryGetValue(filename, out fileLock))
  48. {
  49. fileLock = new SemaphoreSlim(1,1);
  50. _locks[filename] = fileLock;
  51. }
  52. }
  53. return fileLock;
  54. }
  55. /// <summary>
  56. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  57. /// </summary>
  58. public void Dispose()
  59. {
  60. Dispose(true);
  61. }
  62. /// <summary>
  63. /// Releases unmanaged and - optionally - managed resources.
  64. /// </summary>
  65. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  66. protected virtual void Dispose(bool dispose)
  67. {
  68. if (dispose)
  69. {
  70. DisposeLocks();
  71. }
  72. }
  73. /// <summary>
  74. /// Disposes the locks.
  75. /// </summary>
  76. private void DisposeLocks()
  77. {
  78. lock (_locks)
  79. {
  80. foreach (var semaphore in _locks.Values)
  81. {
  82. semaphore.Dispose();
  83. }
  84. _locks.Clear();
  85. }
  86. }
  87. }
  88. }