Mutex.cs 2.1 KB

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