Provides a cross-process object allowing easy dection of application instances (e.g., for use by installers and update tools).
System.Threading.Mutex is intended for synchronizing access to shared resources while this class is intended to detect application instances.
Example #1
0
        public void TestProbeCreateClose()
        {
            Skip.IfNot(WindowsUtils.IsWindowsNT, reason: "AppMutexes are only available on the Windows NT platform.");

            string mutexName = "unit-tests-" + Path.GetRandomFileName();

            AppMutex.Probe(mutexName).Should().BeFalse();
            var mutex = AppMutex.Create(mutexName);

            AppMutex.Probe(mutexName).Should().BeTrue();
            mutex.Close();
            AppMutex.Probe(mutexName).Should().BeFalse();
        }
Example #2
0
        public static bool Create([NotNull, Localizable(false)] string name, out AppMutex mutex)
        {
            #region Sanity checks
            if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
            #endregion

            if (!WindowsUtils.IsWindowsNT)
            {
                mutex = null;
                return false;
            }

            bool existingMutex = false;

            IntPtr handle1 = IntPtr.Zero, handle2 = IntPtr.Zero;
            try
            {
                if (WindowsMutex.Create("Global\\" + name, out handle1))
                {
                    existingMutex = true;
                    Log.Debug("Opened existing global mutex: " + name);
                }
                else Log.Debug("Created global mutex: " + name);
            }
                #region Error handling
            catch (Win32Exception ex)
            {
                Log.Warn(ex.Message);
            }
            #endregion

            try
            {
                if (WindowsMutex.Create(name, out handle2))
                {
                    existingMutex = true;
                    Log.Debug("Opened existing local mutex: " + name);
                }
                else Log.Debug("Created local mutex: " + name);
            }
                #region Error handling
            catch (Win32Exception ex)
            {
                Log.Warn(ex.Message);
            }
            #endregion

            mutex = new AppMutex(new[] {handle1, handle2});
            return existingMutex;
        }