LockExtensions.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. namespace Abp.Threading.Extensions
  3. {
  4. /// <summary>
  5. /// Extension methods to make locking easier.
  6. /// </summary>
  7. public static class LockExtensions
  8. {
  9. /// <summary>
  10. /// Executes given <paramref name="action"/> by locking given <paramref name="source"/> object.
  11. /// </summary>
  12. /// <param name="source">Source object (to be locked)</param>
  13. /// <param name="action">Action (to be executed)</param>
  14. public static void Locking(this object source, Action action)
  15. {
  16. lock (source)
  17. {
  18. action();
  19. }
  20. }
  21. /// <summary>
  22. /// Executes given <paramref name="action"/> by locking given <paramref name="source"/> object.
  23. /// </summary>
  24. /// <typeparam name="T">Type of the object (to be locked)</typeparam>
  25. /// <param name="source">Source object (to be locked)</param>
  26. /// <param name="action">Action (to be executed)</param>
  27. public static void Locking<T>(this T source, Action<T> action) where T : class
  28. {
  29. lock (source)
  30. {
  31. action(source);
  32. }
  33. }
  34. /// <summary>
  35. /// Executes given <paramref name="func"/> and returns it's value by locking given <paramref name="source"/> object.
  36. /// </summary>
  37. /// <typeparam name="TResult">Return type</typeparam>
  38. /// <param name="source">Source object (to be locked)</param>
  39. /// <param name="func">Function (to be executed)</param>
  40. /// <returns>Return value of the <paramref name="func"/></returns>
  41. public static TResult Locking<TResult>(this object source, Func<TResult> func)
  42. {
  43. lock (source)
  44. {
  45. return func();
  46. }
  47. }
  48. /// <summary>
  49. /// Executes given <paramref name="func"/> and returns it's value by locking given <paramref name="source"/> object.
  50. /// </summary>
  51. /// <typeparam name="T">Type of the object (to be locked)</typeparam>
  52. /// <typeparam name="TResult">Return type</typeparam>
  53. /// <param name="source">Source object (to be locked)</param>
  54. /// <param name="func">Function (to be executed)</param>
  55. /// <returns>Return value of the <paramnref name="func"/></returns>
  56. public static TResult Locking<T, TResult>(this T source, Func<T, TResult> func) where T : class
  57. {
  58. lock (source)
  59. {
  60. return func(source);
  61. }
  62. }
  63. }
  64. }