public void SingleThread_MultipleAcquireRelease( ) { using (var mutex = new NamedMutex("Global\\TestMutex", null)) { Assert.IsNotNull(mutex, "The mutex should not be null"); bool isAcquired = mutex.Acquire(0); Assert.IsTrue(isAcquired, "The mutex should be acquired"); mutex.Release( ); isAcquired = mutex.Acquire(0); Assert.IsTrue(isAcquired, "The mutex should be acquired"); isAcquired = mutex.Acquire(0); Assert.IsTrue(isAcquired, "The mutex should be acquired"); mutex.Release( ); isAcquired = mutex.Acquire(0); Assert.IsTrue(isAcquired, "The mutex should be acquired"); isAcquired = mutex.Acquire(0); Assert.IsTrue(isAcquired, "The mutex should be acquired"); mutex.Release( ); } }
static void Main() { Boolean firstInstance; using (NamedMutex mx = new NamedMutex(false, "2D2EBFAC-543A-4FE8-A4E6-D88F5A76B2A1", out firstInstance)) { if (firstInstance) { try { ScannerProxy.ScannerAPI.SetLabelSuffix(); Boolean start = true; try { Assembly.Load("System.Data.SqlServerCe, Version=3.5.0.0, Culture=neutral, PublicKeyToken=3BE235DF1C8D2AD3"); } catch { start = false; MyClass.ShowError("Не установлен Sql Server Compact 3.5"); } if (start) { Application.Run(new FormMain()); } GC.KeepAlive(mx); } finally { ScannerProxy.ScannerAPI.RestoreLabelSuffix(); } } } }
/// <summary> /// Begins running a standard application message loop on the current thread, and makes the specified form visible. /// </summary> /// <param name="mainForm">Form on which main message loop runs</param> /// <param name="runAsSingletonApp">When <b>true</b>, if an existing instance of the app is already running, the current application instance will simply exit and the already running app will come to the fore</param> /// <param name="displayMainForm">When set to true, the main form will be automatically displayed, else the app will be responsible for showing the Form</param> public static void Run(Form mainForm, bool runAsSingletonApp, bool displayMainForm) { bool isNew = true; NamedMutex m = new NamedMutex(true, Application2.StartupPath, out isNew); if (runAsSingletonApp) { if (!isNew) { // activate the existing instance EventWaitHandle wh = new EventWaitHandle(false, EventResetMode.AutoReset, Application2.StartupPath); wh.Set(); return; } else { //create a thread to wait for any subsequent instances to signal remoteActivateThread = new Thread(new System.Threading.ThreadStart(RemoteActivateThreadProc)); remoteActivateThread.IsBackground = true; remoteActivateThread.Name = "SDF Application2 UI thread"; remoteActivateThread.Start(); // create a filter to track the currently active form so if // we get reactivated from another instance attempting to run // we know what Form to put topmost currentFormFilter = new CurrentFormMessageFilter(); AddMessageFilter(currentFormFilter); } } // if (runAsSingletonApp) mainForm.Closed += new EventHandler(MainFormExit); Application2.mainForm = mainForm; RunMessageLoop(displayMainForm); }
public void Constructor_ValidName( ) { using (var mutex = new NamedMutex("TestMutex", null)) { Assert.IsNotNull(mutex, "The mutex should not be null"); } }
static void Main() { bool isNew; NamedMutex mutex = new NamedMutex(true, WS_RUNNING_MUTEX_NAME, out isNew); // if we're already running, don't try to start again if (!isNew) { return; } // check for previous fatal errors FatalErrorCheck(); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // make sure any non-Padarn web server is shut down ServiceCollection services = ServiceCollection.GetServices(); foreach (Service svc in services) { if (svc.Prefix.IndexOf("HTP") >= 0) { svc.Unload(); break; } } //Run the host application Application.Run(new ControlForm()); mutex.Close(); }
public void SingleThread_InvalidAcquireTimeout( ) { using (var mutex = new NamedMutex("TestMutex", null)) { Assert.IsNotNull(mutex, "The mutex should not be null"); mutex.Acquire(-10); } }
public void SingleThread_SingleAcquireAutoRelease( ) { using (var mutex = new NamedMutex("TestMutex", null)) { Assert.IsNotNull(mutex, "The mutex should not be null"); bool isAcquired = mutex.Acquire( ); Assert.IsTrue(isAcquired, "The mutex should be acquired"); } }
/// <summary> /// Begins running a standard application message loop on the current thread, without a form. /// </summary> /// <param name="runAsSingletonApp">When <b>true</b>, if an existing instance of the app is already running, the current application instance will simply exit</param> public static void Run(bool runAsSingletonApp) { bool isNew = true; NamedMutex m = new NamedMutex(true, Application2.StartupPath, out isNew); if (isNew) { Run(); } }
private void menuItemStopDaemon_Click(object sender, EventArgs e) { // Just to make sure that a daemon is running... using (NamedMutex mutex = new NamedMutex(false, "Global\\LocationScheduler\\LSCore")) { if (!mutex.WaitOne(0, false)) { // Could not grab mutex-> daemon is running _MsgQueueMgr.Write(NotifMessages.NOTIF_STOP); } else { SenseAPIs.SenseMessageBox.Show("No daemon running!", "Error", SenseMessageBoxButtons.OK); } } }
static void Main() { /* * bool createdNew = true; * mutexForCheckMultipleApp = new Calbee.Infra.Helper.Threading.NamedMutex(false, @"Calbee", out createdNew); * * if (createdNew) * { * Application.Run(new Authentication.frmLogin()); * } * else * { * MsgBox.DialogWarning("The program is running. Cannot open more than 1 program"); * } */ try { if (Calbee.Infra.Common.Constants.IConstants.platformWinCE.Equals("Y")) { // For Windows CE using (NamedMutex mutex = new NamedMutex(false, "Global\\" + @"\Calbee.WMS.UI\Calbee.WMS.UI")) { if (mutex.WaitOne(0, false)) { //not already running Application.Run(new Authentication.frmLogin()); } else { // already running MsgBox.DialogWarning("Calbee program is already running."); return; } } } else { // For Windows Runtime Application.Run(new Authentication.frmLogin()); } } catch (Exception) { Application.Run(new Authentication.frmConfigWebService()); } }
/// <summary> /// This constructs a FileEventLog object. /// </summary> /// <param name="folder">The path of the event log folder.</param> /// <param name="filename">The name of the default log file.</param> public FileEventLogWriter(string folder, string filename) { if (string.IsNullOrEmpty(folder)) { throw new ArgumentNullException(nameof(folder)); } if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException(nameof(filename)); } TraceEnabled = true; InformationEnabled = true; WarningEnabled = true; ErrorEnabled = true; // Initialise the folder and filename _folder = folder; _filename = filename; _path = Path.Combine(_folder, _filename); _baseFileName = Path.GetFileNameWithoutExtension(_filename); _baseExtension = Path.GetExtension(_filename); // Derive the name of the mutex from the folder name. // FileEventLog objects with different log folders // will have different mutex names. var syncMutexName = GetLogMutexName(folder); // Lazy mutex factory _syncMutex = new NamedMutex(syncMutexName); _eventLogEntryQueue = new ConcurrentQueue <EventLogEntry>(); // Initialise the thread worker. _eventLogWorkerThread = new Thread(WriteEntriesWorker) { Name = "FileEventLogWorkerThread", IsBackground = true }; _eventLogWorkerThread.Start( ); }
public void MultipleThreads_AbandonedMutex( ) { // Create a thread that abandons a mutex var t = new Thread(() => { //Create a mutex and do not release it. var mutex = new NamedMutex("AbandonedMutex"); mutex.Acquire( ); }); t.Start( ); // Wait for the thread to finish t.Join( ); using (var mutex = new NamedMutex("AbandonedMutex")) { Assert.IsTrue(mutex.Acquire( ), "Abandoned mutex should be acquired"); } }
/// <summary> /// Loads the log entries from the specified log file. /// </summary> /// <param name="path"> /// A string containing the path of the log file to examine. /// </param> /// <returns> /// A dictionary of the entries contained within the specified log file. /// </returns> private static EventLogEntryCollection LoadLog(string path) { var eventLogEntries = new EventLogEntryCollection( ); // Check that the log file exists if (File.Exists(path)) { // Create a mutex for this folder. string mutexName = FileEventLogWriter.GetLogMutexName(path); using (var logMutex = new NamedMutex(mutexName)) { if (logMutex.Acquire( )) { eventLogEntries = LoadLog_Impl(path); } } } return(eventLogEntries); }
static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += FMSC.Utility.ErrorHandling.ErrorHandlers.UnhandledException; using (NamedMutex mutex = new NamedMutex(false, "Global\\" + "FScruiser")) { if (mutex.WaitOne(0, false)) { //not already running DialogService.Instance = new WinFormsDialogService(); using (SoundService.Instance = new WinFormsSoundService()) using (ViewController viewController = new ViewController()) using (ApplicationController appController = new ApplicationController(viewController)) { if (args.Length > 1) { appController.OpenFile(args[1]); } viewController.Run(); } Debug.Close(); } else { //is already running string message = "FScruiser is already running\r\n"; if (ViewController.PlatformType == FMSC.Controls.PlatformType.WM) { message += "To halt or activate background programs, go to Settings->System->Memory"; } MessageBox.Show(message); return; } } }
static void Main(string[] args) { Globals.WriteToDebugFile("--- Init ---"); using (NamedMutex mutex = new NamedMutex(false, "Global\\LocationScheduler\\LSCore")) { if (!mutex.WaitOne(0, false)) { Globals.WriteToDebugFile("Instance already running"); return; } GC.Collect(); // We have to force the cursor to the default one, otherwise // it will stay in the "wait" cursor". This is probably because // of the fact that the thread locks right at the startup... Cursor.Current = Cursors.Default; TasksMonitor tm = new TasksMonitor(); } Globals.WriteToDebugFile("--- Shutdown ---"); }
public void MultipleThreads_TimedOutMutex( ) { using (AutoResetEvent evt = new AutoResetEvent(false)) using (AutoResetEvent evt2 = new AutoResetEvent(false)) { // Create a thread that abandons a mutex var t = new Thread(() => { using (var mutex = new NamedMutex("TestMutex")) { // Hold the mutex mutex.Acquire( ); // ReSharper disable once AccessToDisposedClosure evt2.Set( ); // ReSharper disable once AccessToDisposedClosure evt.WaitOne( ); } }) { IsBackground = true }; t.Start( ); evt2.WaitOne(500); using (var mutex = new NamedMutex("TestMutex")) { // Attempt to acquire the mutex after waiting 100 ms // This should fail as the thread above is holding the mutex for 10 seconds. Assert.IsFalse(mutex.Acquire(100), "Test mutex should not be acquired"); evt.Set( ); } } }
/// <summary> /// Thread proc method /// </summary> private void ThreadProc( ) { _startEvent.WaitOne( ); bool finished = false; while (!finished) { using (var mutex = new NamedMutex("TestMutex")) { if (mutex.Acquire( )) { if (_sharedObjectsList.Count == 0) { finished = true; } else { // Get the first object from the list SharedObject so = _sharedObjectsList[0]; // If it belongs to this thread task it and remove it from the list if (so.OwnerThread == Thread.CurrentThread.Name) { _localObjectsDictionary[so.Id] = so; _sharedObjectsList.RemoveAt(0); } } } if (!_autoRelease) { mutex.Release( ); } } } }
public void Run() { var processName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().GetName().CodeBase); // create the MMF m_mmf = MemoryMappedFile.CreateInMemoryMap(SharedMapName, MaxMapSize); // create a shared mutex m_mutex = new NamedMutex(false, SharedMutexName); // create a data-ready event m_dataReady = new EventWaitHandle(false, EventResetMode.ManualReset, DataReadyEventName); // fire up a "listener" new System.Threading.Thread(ReadProc) { IsBackground = true, Name = "MMF Peer Reader" } .Start(); Console.WriteLine("Memory Mapped File Created. Enter text to send to peer(s)"); // wait for user input while (true) { var input = Console.ReadLine(); if (input == null) { Thread2.Sleep(5000); input = GetMockInput(); Debug.WriteLine(string.Format("Platform does not have a Console installed. Sending mock data '{0}'", input)); } if (input == "exit") { break; } // prefix our process name so we can tell who sent the data input = processName + ":" + input; // grab the mutex if (!m_mutex.WaitOne(5000, false)) { Console.WriteLine("Unable to acquire mutex. Send Abandoned"); Debug.WriteLine("Unable to acquire mutex. Send Abandoned"); continue; } // mark as "sending" so the listener will ignore what we send Sending = true; // create a "packet" (length + data) var packet = new byte[4 + input.Length]; Buffer.BlockCopy(BitConverter.GetBytes(input.Length), 0, packet, 0, 4); Buffer.BlockCopy(Encoding.ASCII.GetBytes(input), 0, packet, 4, input.Length); // write the packet at the start m_mmf.Seek(0, System.IO.SeekOrigin.Begin); m_mmf.Write(packet, 0, packet.Length); // notify all clients that data is ready (manual reset events will release all waiting clients) m_dataReady.Set(); // yield to allow the receiver to unblock and check the "Sending" flag Thread2.Sleep(1); // reset the event m_dataReady.Reset(); // unmark "sending" Sending = false; // release the mutex m_mutex.ReleaseMutex(); } }