Mutex.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 Microsoft.Win32;
  5. using Microsoft.Win32.SafeHandles;
  6. using System.Diagnostics;
  7. using System.Diagnostics.CodeAnalysis;
  8. using System.IO;
  9. using System.Runtime.InteropServices;
  10. namespace System.Threading
  11. {
  12. /// <summary>
  13. /// Synchronization primitive that can also be used for interprocess synchronization
  14. /// </summary>
  15. public sealed partial class Mutex : WaitHandle
  16. {
  17. public Mutex(bool initiallyOwned, string? name, out bool createdNew)
  18. {
  19. CreateMutexCore(initiallyOwned, name, out createdNew);
  20. }
  21. public Mutex(bool initiallyOwned, string? name)
  22. {
  23. CreateMutexCore(initiallyOwned, name, out _);
  24. }
  25. public Mutex(bool initiallyOwned)
  26. {
  27. CreateMutexCore(initiallyOwned, null, out _);
  28. }
  29. public Mutex()
  30. {
  31. CreateMutexCore(false, null, out _);
  32. }
  33. private Mutex(SafeWaitHandle handle)
  34. {
  35. SafeWaitHandle = handle;
  36. }
  37. public static Mutex OpenExisting(string name)
  38. {
  39. switch (OpenExistingWorker(name, out Mutex? result))
  40. {
  41. case OpenExistingResult.NameNotFound:
  42. throw new WaitHandleCannotBeOpenedException();
  43. case OpenExistingResult.NameInvalid:
  44. throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
  45. case OpenExistingResult.PathNotFound:
  46. throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, name));
  47. default:
  48. Debug.Assert(result != null, "result should be non-null on success");
  49. return result;
  50. }
  51. }
  52. public static bool TryOpenExisting(string name, [NotNullWhen(true)] out Mutex? result) =>
  53. OpenExistingWorker(name, out result) == OpenExistingResult.Success;
  54. }
  55. }