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