public bool ForceOnce() { Process process = Process.GetProcessById(_processId); if (process == null || process.HasExited) throw new InvalidOperationException("Cannot force focus, process is not running"); _waitHandle = new AutoResetEvent(false); try { Win32.EnumWindowsProc ewc = CheckWindow; int focusedId = Win32.GetForegroundWindowPID(); if (focusedId != _processId) { _windowHandle = IntPtr.Zero; Win32.EnumerateWindows(ewc, IntPtr.Zero); bool waitResult = _waitHandle.WaitOne(5000, false); if (waitResult && _windowHandle != IntPtr.Zero) return Win32.SetForegroundWindow(_windowHandle, true); } } finally { _waitHandle.Close(); _waitHandle = null; } return false; }
/// <summary> /// Creates the single instance. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public static bool IsFirstInstance(string name) { EventWaitHandle eventWaitHandle = null; string eventName = string.Format("{0}-{1}", Environment.MachineName, name); var isFirstInstance = false; try { // try opening existing wait handle eventWaitHandle = EventWaitHandle.OpenExisting(eventName); } catch { // got exception = handle wasn't created yet isFirstInstance = true; } if (isFirstInstance) { // init handle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName); // register wait handle for this instance (process) ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, WaitOrTimerCallback, null, Timeout.Infinite, false); eventWaitHandle.Close(); } return isFirstInstance; }
private static void Main(string[] args) { //Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("he"); if (args.Any(s => (s == "driverinstall") || (s == "-driverinstall"))) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new WelcomeDialog()); return; } GCSettings.LatencyMode = GCLatencyMode.LowLatency; try { Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High; } catch { // Ignore problems raising the priority. } try { // another instance is already running if OpenExsting succeeds. threadComEvent = EventWaitHandle.OpenExisting(singleAppComEventName); threadComEvent.Set(); // signal the other instance. threadComEvent.Close(); return; // return immediatly. } catch { /* don't care about errors */ } // Create the Event handle threadComEvent = new EventWaitHandle(false, EventResetMode.AutoReset, singleAppComEventName); CreateInterAppComThread(); if (mutex.WaitOne(TimeSpan.Zero, true)) { RootHub = new ControlService(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new DS4Form(args)); mutex.ReleaseMutex(); } // End the communication thread. singleAppComThread.CancelAsync(); while (singleAppComThread.IsBusy) { Thread.Sleep(50); } threadComEvent.Close(); }
/// <summary> /// Creates the single instance. /// </summary> /// <param name="name">The name.</param> /// <param name="callback">The callback.</param> /// <returns></returns> public static bool CreateSingleInstance(string name, String[] args, EventHandler<InstanceCallbackEventArgs> callback) { Logger.LogDebug("Workbench", 1, "Creating single instance setup\n"); EventWaitHandle eventWaitHandle = null; string eventName = String.Format("{0}.{1}.{2}", Environment.MachineName, Environment.UserName, name); InstanceProxy.IsFirstInstance = false; InstanceProxy.CommandLineArgs = args; try { // Try opening existing wait handle. Logger.LogDebug("Workbench", 2, "Trying to open existing event wait handle\n"); eventWaitHandle = EventWaitHandle.OpenExisting(eventName); } catch { // Got exception => handle wasn't created yet. InstanceProxy.IsFirstInstance = true; } if (InstanceProxy.IsFirstInstance) { Logger.LogDebug("Workbench", 2, "This is the first application instance\n"); // Since this is the first instance we need to set up our communication infrastructure. eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName); ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, WaitOrTimerCallback, callback, Timeout.Infinite, false); eventWaitHandle.Close(); // Register shared type (used to pass data between processes). RegisterRemoteType(name); } else { Logger.LogDebug("Workbench", 2, "Another application instance is already running\n"); // We are second in a row, so pass application arguments to the shared object and quit. UpdateRemoteObject(name); if (eventWaitHandle != null) eventWaitHandle.Set(); } return InstanceProxy.IsFirstInstance; }
/// <summary> /// Creates the single instance. /// </summary> /// <param name="name">The name.</param> /// <param name="callback">The callback.</param> /// <returns></returns> public static bool CreateSingleInstance(string name, EventHandler<InstanceCallbackEventArgs> callback) { EventWaitHandle eventWaitHandle = null; string eventName = string.Format("{0}-{1}", Environment.MachineName, name); InstanceProxy.IsFirstInstance = false; InstanceProxy.CommandLineArgs = Environment.GetCommandLineArgs(); try { // try opening existing wait handle eventWaitHandle = EventWaitHandle.OpenExisting(eventName); } catch { // got exception = handle wasn't created yet InstanceProxy.IsFirstInstance = true; } if (InstanceProxy.IsFirstInstance) { // init handle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName); // register wait handle for this instance (process) ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, WaitOrTimerCallback, callback, Timeout.Infinite, false); eventWaitHandle.Close(); // register shared type (used to pass data between processes) RegisterRemoteType(name); } else { // pass console arguments to shared object UpdateRemoteObject(name); // invoke (signal) wait handle on other process if (eventWaitHandle != null) eventWaitHandle.Set(); // kill current process Environment.Exit(0); } return InstanceProxy.IsFirstInstance; }
internal static void Make(String name, Application app) { EventWaitHandle eventWaitHandle = null; String eventName = Environment.MachineName + "-" + name; bool isFirstInstance = false; try { eventWaitHandle = EventWaitHandle.OpenExisting(eventName); } catch { // it's first instance isFirstInstance = true; } if (isFirstInstance) { eventWaitHandle = new EventWaitHandle( false, EventResetMode.AutoReset, eventName); ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, waitOrTimerCallback, app, Timeout.Infinite, false); // not need more eventWaitHandle.Close(); // !!! delete it if not use setFirstArgs(); } else { // !!! delete it if not use setArgs(); eventWaitHandle.Set(); // For that exit no interceptions Environment.Exit(0); } }
private void Dispose(bool disposing) { if (disposing) { if (fDisposed) { throw new ObjectDisposedException(null); } if (WaitingReadCount > 0 || WaitingUpgradeCount > 0 || WaitingWriteCount > 0) { throw new SynchronizationLockException(SR.GetString(SR.SynchronizationLockException_IncorrectDispose)); } if (IsReadLockHeld || IsUpgradeableReadLockHeld || IsWriteLockHeld) { throw new SynchronizationLockException(SR.GetString(SR.SynchronizationLockException_IncorrectDispose)); } if (writeEvent != null) { writeEvent.Close(); writeEvent = null; } if (readEvent != null) { readEvent.Close(); readEvent = null; } if (upgradeEvent != null) { upgradeEvent.Close(); upgradeEvent = null; } if (waitUpgradeEvent != null) { waitUpgradeEvent.Close(); waitUpgradeEvent = null; } fDisposed = true; } }
/// <summary> /// /// </summary> /// <param name="uniqueName"></param> /// <returns>True is another instance is already running. False otherwise</returns> public static Boolean CheckForOtherApp(String uniqueName) { SingleAppComEventName = uniqueName; try { // another instance is already running threadComEvent = EventWaitHandle.OpenExisting(SingleAppComEventName); threadComEvent.Set(); // signal the other instance. threadComEvent.Close(); return true; // return immediatly. } catch { /* don't care about errors */ } // Create the Event handle threadComEvent = new EventWaitHandle(false, EventResetMode.AutoReset, SingleAppComEventName); // make sure the resources are cleaned up afterwards. cleanupCode = new CleanupCode(); CreateInterAppComThread(); return false; }
public ActivatorHost(string guid, int processId, ProcessDomainSetup setup) { SetupDllDirectories(setup); var serverProvider = new BinaryServerFormatterSinkProvider { TypeFilterLevel = setup.TypeFilterLevel }; var clientProvider = new BinaryClientFormatterSinkProvider(); _process = Process.GetProcessById(processId); var properties = new Hashtable(); properties["portName"] = string.Format(ServerChannelName, guid); properties["name"] = string.Format(ServerChannelName, guid); properties["rejectRemoteRequests"] = true; setup.Remoting.ApplyServerProperties(properties); _channel = new IpcChannel(properties, clientProvider, serverProvider); ChannelServices.RegisterChannel(_channel, false); RemotingConfiguration.RegisterWellKnownServiceType(typeof(Activator), ActivatorName, WellKnownObjectMode.Singleton); EventWaitHandle serverStartedHandle = null; try { bool created; serverStartedHandle = new EventWaitHandle(false, EventResetMode.ManualReset, string.Format(EventName, guid), out created); if (created) { throw new Exception("Event handle did not exist for remote process"); } serverStartedHandle.Set(); } finally { if (serverStartedHandle != null) { serverStartedHandle.Close(); } } }
void RunThread() { var canRun = true; var e = KeyEvent.Empty; var inputEvent = new EventWaitHandle(false, EventResetMode.AutoReset, inputEventName); try { OnActivated(); } catch (Exception ex) { canRun = false; OnScriptError(ex); } canRun = BeforeRunThread(); while (IsRunning) { if (canRun) { for (e = GetKeyEvent(); e.IsEmpty == false; e = GetKeyEvent()) { OnKeyEvent(e); if (!IsRunning) { break; } } } inputEvent.WaitOne(); } //ClearKeyEvents(); SetBacklightColor(128, 255, 255); lcd.RemoveFromFront(); inputEvent.Close(); AfterRunThread(); var inputExit = new EventWaitHandle(false, EventResetMode.AutoReset, inputExitName); inputExit.Set(); inputExit.Close(); }
private Process CreateAddInProcess() { Process addInProcess = new Process(); Guid guid = Guid.NewGuid(); String args = String.Format(CultureInfo.InvariantCulture, "/guid:{0} /pid:{1}", guid, Process.GetCurrentProcess().Id); addInProcess.StartInfo.CreateNoWindow = true; addInProcess.StartInfo.UseShellExecute = false; addInProcess.StartInfo.Arguments = args; addInProcess.StartInfo.FileName = _pathToAddInProcess; #if _DEBUG String debuggerPath = Environment.GetEnvironmentVariable("COMPLUS_AddInProcessDebugger"); String debuggerArgs = Environment.GetEnvironmentVariable("COMPLUS_AddInProcessDebuggerArgs"); if(!String.IsNullOrEmpty(debuggerPath)) { addInProcess.StartInfo.Arguments = ""; if(!String.IsNullOrEmpty(debuggerArgs)) { addInProcess.StartInfo.Arguments = debuggerArgs + " "; } addInProcess.StartInfo.Arguments += _pathToAddInProcess + " " + args; addInProcess.StartInfo.FileName = debuggerPath; } #endif // wait until it's ready EventWaitHandle readyEvent = new EventWaitHandle(false, EventResetMode.ManualReset, "AddInProcess:" + guid); addInProcess.Start(); bool success = readyEvent.WaitOne(_startupTimeout, false); readyEvent.Close(); if (!success) { // Here's an effort to avoid leaving a half-baked process around if possible. try { addInProcess.Kill(); } catch (Exception) {} throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Res.CouldNotCreateAddInProcess, _startupTimeout.ToString())); } _guid = guid; return addInProcess; }
static void Main(string[] args) { System.Configuration.Install.InstallContext _args = new System.Configuration.Install.InstallContext(null, args); if (_args.IsParameterTrue("debug")) { System.Console.WriteLine("Wait for debugger, press any key to continue..."); System.Console.ReadKey(); } logIt(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileVersionInfo.ToString()); // dump args logIt(string.Format("called by arg: ({0})", args.Length)); foreach (string s in args) { logIt(s); } System.Threading.EventWaitHandle e = null; if (_args.IsParameterTrue("start-service")) { // start service try { e = System.Threading.EventWaitHandle.OpenExisting(androidServer_Event_Name); e.Close(); logIt("Instance already started."); } catch (WaitHandleCannotBeOpenedException) { e = new EventWaitHandle(false, EventResetMode.ManualReset, androidServer_Event_Name); //argMap.Add("quitEvent", e); SerialManager.Init(); start(args, e); e.Close(); } catch (Exception) { } } else if (_args.IsParameterTrue("kill-service")) { // stop service try { e = System.Threading.EventWaitHandle.OpenExisting(androidServer_Event_Name); if (e != null) { e.Set(); } } catch (Exception) { } } else { System.Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().GetName().Name); System.Console.WriteLine("-start-service: to start the service"); System.Console.WriteLine("-kill-service: to stop the service"); } // SerialManager serialManager = new SerialManager(); // serialManager.Init(); }
// Create a new wait handle identified by the prSearchKey and wait for the // Workshare.SendLink.Client.exe to signal it after the upload has completed. private void CreateSubmitWorkerThread(string prSearchKey) { Logger.LogInfo("SendLink deterministic send waiting for upload to complete. PrSearchKey = " + prSearchKey); var submitMessage = new Thread(new ThreadStart(delegate { var eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, prSearchKey); _submitWaitHandles.Add(eventWaitHandle); eventWaitHandle.WaitOne(); Logger.LogInfo("SendLink deterministic send notified upload complete and mail can be submited. PrSearchKey = " + prSearchKey); if (_disposing) { return; } lock (_lock) { SubmitNonDeferredItems(); } _submitWaitHandles.Remove(eventWaitHandle); eventWaitHandle.Close(); })); submitMessage.Start(); }
/// <summary> /// This function launches a new node given a node index /// </summary> private void LaunchNode(int nodeIndex) { EventWaitHandle nodeReadyEvent = null; string msbuildLocation = Path.Combine(locationOfMSBuildExe, "MSBuild.exe"); ErrorUtilities.VerifyThrow(File.Exists(msbuildLocation),"Msbuild.exe cannot be found at: "+msbuildLocation); bool exitedDueToError = true; try { NativeMethods.STARTUPINFO startInfo = new NativeMethods.STARTUPINFO(); startInfo.cb = Marshal.SizeOf(startInfo); uint dwCreationFlags = NativeMethods.NORMAL_PRIORITY_CLASS; if (!Engine.debugMode) { startInfo.hStdError = NativeMethods.InvalidHandle; startInfo.hStdInput = NativeMethods.InvalidHandle; startInfo.hStdOutput = NativeMethods.InvalidHandle; startInfo.dwFlags = NativeMethods.STARTF_USESTDHANDLES; dwCreationFlags = dwCreationFlags | NativeMethods.CREATE_NO_WINDOW; } NativeMethods.SECURITY_ATTRIBUTES pSec = new NativeMethods.SECURITY_ATTRIBUTES(); NativeMethods.SECURITY_ATTRIBUTES tSec = new NativeMethods.SECURITY_ATTRIBUTES(); pSec.nLength = Marshal.SizeOf(pSec); tSec.nLength = Marshal.SizeOf(tSec); NativeMethods.PROCESS_INFORMATION pInfo = new NativeMethods.PROCESS_INFORMATION(); string appName = msbuildLocation; // Repeat the executable name as the first token of the command line because the command line // parser logic expects it and will otherwise skip the first argument string cmdLine = msbuildLocation + " /nologo /oldom /nodemode:" + nodeData[nodeIndex].NodeNumber; NativeMethods.CreateProcess(appName, cmdLine, ref pSec, ref tSec, false, dwCreationFlags, NativeMethods.NullPtr, null, ref startInfo, out pInfo); nodeReadyEvent = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeActiveEventName(nodeData[nodeIndex].NodeNumber)); // Wait until the node is ready to process the requests if (nodeReadyEvent.WaitOne(launchTimeout, false)) { exitedDueToError = false; } } finally { // Dispose before losing scope if (nodeReadyEvent != null) { nodeReadyEvent.Close(); } if (exitedDueToError) { nodeData[nodeIndex].CommunicationFailed = true; } } }
public void Open(bool isReconnecting) { if (!this.closed) { this.listenerEndPoint = this.HandleServiceStart(isReconnecting); if (string.IsNullOrEmpty(this.listenerEndPoint)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("Sharing_EmptyListenerEndpoint", new object[] { this.serviceName }))); } if (!this.closed) { this.LookupListenerSid(); EventWaitHandle handle = null; bool flag = false; lock (this.ThisLock) { try { bool flag2; this.CreateControlProxy(); EventWaitHandleSecurity eventSecurity = new EventWaitHandleSecurity(); eventSecurity.AddAccessRule(new EventWaitHandleAccessRule(this.listenerUniqueSid, EventWaitHandleRights.Modify, AccessControlType.Allow)); handle = new EventWaitHandle(false, EventResetMode.ManualReset, @"Global\" + this.securityEventName, out flag2, eventSecurity); if (!flag2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("SharedManagerBase", new object[] { this.serviceName, System.ServiceModel.SR.GetString("SharedManagerServiceSecurityFailed") }))); } this.Register(); if (!handle.WaitOne(0, false)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("SharedManagerBase", new object[] { this.serviceName, System.ServiceModel.SR.GetString("SharedManagerServiceSecurityFailed") }))); } if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, 0xa0005, System.ServiceModel.SR.GetString("TraceCodePortSharingListening")); } this.opened = true; flag = true; } finally { if (handle != null) { handle.Close(); } if (!flag) { this.Cleanup(true, TimeSpan.Zero); this.closed = true; } } } } } }
//-------------------------------------------------------------------------- // Data reception //-------------------------------------------------------------------------- unsafe void ReadThread(ThreadContext ctx) { System.Threading.Thread.CurrentThread.Name = "BluetoothConnection.ReadThread"; EventWaitHandle asyncReadCompleteEvent = new EventWaitHandle(false, System.Threading.EventResetMode.ManualReset); NativeOverlapped* pNativeOverlapped = null; byte[] rgbBuffer = new byte[64]; try { WaitHandle[] waitHandles = new WaitHandle[2]; waitHandles[0] = asyncReadCompleteEvent; waitHandles[1] = ctx.StopEvent; // while (!ctx.StopRequest) { // Issue an async read // asyncReadCompleteEvent.Reset(); Overlapped overlapped = new Overlapped(0, 0, asyncReadCompleteEvent.SafeWaitHandle.DangerousGetHandle(), null); pNativeOverlapped = overlapped.Pack(null, rgbBuffer); int cbRead = 0; bool fSuccess = ReadFile(this.hSerialPort, rgbBuffer, rgbBuffer.Length, out cbRead, new IntPtr(pNativeOverlapped)); readThreadRunning.Set(); if (!fSuccess) { int err = Marshal.GetLastWin32Error(); if (err != ERROR_IO_PENDING) ThrowWin32Error(err); } // Wait until either the async read completes or we're asked to stop int iWait = WaitHandle.WaitAny(waitHandles); // Process according to which event fired switch (iWait) { case 0: // Async read completed { ThrowIfFail(GetOverlappedResult(this.hSerialPort, new IntPtr(pNativeOverlapped), ref cbRead, System.Convert.ToByte(true))); // Program.Trace("async read complete: 0x{0:08X} 0x{1:08X} cb={2}", new IntPtr(pNativeOverlapped), this.hSerialPort, cbRead); // Record the new data and process any packets that are now complete this.RecordIncomingData(rgbBuffer, cbRead); ProcessPacketIfPossible(); System.Threading.Overlapped.Free(pNativeOverlapped); pNativeOverlapped = null; } break; case 1: // StopEvent break; // end switch } } } finally { CancelIo(this.hSerialPort); asyncReadCompleteEvent.Close(); if (pNativeOverlapped != null) { System.Threading.Overlapped.Free(pNativeOverlapped); pNativeOverlapped = null; } } }
public void Dispose() { wakeUp.Close(); restart.Close(); gThread.Abort(); }
static int Main(string[] args) // :обновление { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.ExecutablePath)); repairUpdateExe(); var repair = args.Length == 0 || (args.Length == 1 && args[0] == "-repair"); if (Repair(repair) && repair) { Console.WriteLine("repair started - succes"); return(40); } if (args.Length > 5 || args.Length < 4) { writeHelp(); return(1); } mainMutexForLog.WaitOne(); addBootRun(); Semaphore s = null; //new System.Threading.Semaphore(50, 50, "vs8.ru updator semaphore"); Mutex syncSemaphoreMutex = null; int sCount = 0, rCount = 0, mCount = 0; bool updatorUpdate = false; try { if (args[1] == "vs8.ru updator semaphore") { main.Set(); sCount = 50; updatorUpdate = true; } else { sCount = Int32.Parse(args[2]); } if (args[1].Length > 0) { s = new Semaphore(sCount, sCount, args[1]); syncSemaphoreMutex = new Mutex(false, args[1] + " umove sync mutex"); } if (syncSemaphoreMutex != null) { if (!syncSemaphoreMutex.WaitOne(0)) { return(32); } mCount = 1; } var RepairInfo = setRepairInfo(args); if (s != null) { rCount = blockSemaphore(s, sCount); } var returned = umoveProcess(args); if (returned == 0) { Console.WriteLine("success"); } else { Console.WriteLine("failure with code " + returned); } File.AppendAllText(errorLogFileName, String.Format(msgMessage, DateTime.Now, "Исполнено с кодом " + returned, getArgumentsFromArgArray(args))); if (updatorUpdate) { File.AppendAllText(errorLogFileName, String.Format(msgMessage, DateTime.Now, "Стартуем ./updatorvs8.exe -umove", getArgumentsFromArgArray(args))); Process.Start("updatorvs8.exe", "-umove"); } if (args[3].Length > 0) { if (args.Length == 4) { File.AppendAllText(errorLogFileName, String.Format(msgMessage, DateTime.Now, "Стартуем " + args[3], getArgumentsFromArgArray(args))); Process.Start(args[3]); } else { File.AppendAllText(errorLogFileName, String.Format(msgMessage, DateTime.Now, "Стартуем " + args[3] + " " + args[4], getArgumentsFromArgArray(args))); Process.Start(args[3], args[4]); } } ClearRepairInfo(args, RepairInfo); deleteBootRun(); File.AppendAllText(errorLogFileName, String.Format(msgMessage, DateTime.Now, "Исполнено и удалено из аварийного восстановления", getArgumentsFromArgArray(args))); truncateLog(new FileInfo(errorLogFileName)); return(returned); } finally { if (s != null) { releaseSemaphore(s, rCount); s.Close(); } if (syncSemaphoreMutex != null) { if (mCount > 0) { syncSemaphoreMutex.ReleaseMutex(); } syncSemaphoreMutex.Close(); } main.Reset(); main.Close(); mainMutexForLog.ReleaseMutex(); mainMutexForLog.Close(); } }
public void TestElection() { testName = "TestElection"; testHome = testFixtureHome + "/" + testName; client1StartSignal = new AutoResetEvent(false); client2StartSignal = new AutoResetEvent(false); client1ReadySignal = new AutoResetEvent(false); client2ReadySignal = new AutoResetEvent(false); client3StartSignal = new AutoResetEvent(false); client3ReadySignal = new AutoResetEvent(false); masterLeaveSignal = new AutoResetEvent(false); Thread thread1 = new Thread( new ThreadStart(UnstableMaster)); Thread thread2 = new Thread( new ThreadStart(StableClient1)); Thread thread3 = new Thread( new ThreadStart(StableClient2)); Thread thread4 = new Thread( new ThreadStart(StableClient3)); thread1.Start(); Thread.Sleep(1000); thread2.Start(); thread3.Start(); thread4.Start(); thread4.Join(); thread3.Join(); thread2.Join(); thread1.Join(); client1StartSignal.Close(); client2StartSignal.Close(); client1ReadySignal.Close(); client2ReadySignal.Close(); client3ReadySignal.Close(); client3StartSignal.Close(); masterLeaveSignal.Close(); }
private static void StartOrSignal(Action Run) { // get application GUID as defined in AssemblyInfo.cs string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); // unique id for global mutex - Global prefix means it is global to the machine string mutexId = string.Format(useGlobalMutex ? "Global\\{{{0}}}" : "{{{0}}}", appGuid); string SingleAppComEventName = mutexId + "_event"; BackgroundWorker singleAppComThread = null; EventWaitHandle threadComEvent = null; using (var mutex = new Mutex(false, mutexId)) { var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); mutex.SetAccessControl(securitySettings); var hasHandle = false; try { try { hasHandle = mutex.WaitOne(1000, false); if (hasHandle == false) { Debug.WriteLine("Instance already running, timeout expired"); threadComEvent = EventWaitHandle.OpenExisting(SingleAppComEventName); threadComEvent.Set(); // signal the other instance. threadComEvent.Close(); return; } } catch (AbandonedMutexException) { // Log the fact the mutex was abandoned in another process, it will still get aquired hasHandle = true; } threadComEvent = new EventWaitHandle(false, EventResetMode.AutoReset, SingleAppComEventName); singleAppComThread = new BackgroundWorker(); singleAppComThread.WorkerReportsProgress = false; singleAppComThread.WorkerSupportsCancellation = true; singleAppComThread.DoWork += (object sender, DoWorkEventArgs e) => { BackgroundWorker worker = sender as BackgroundWorker; WaitHandle[] waitHandles = new WaitHandle[] { threadComEvent }; while (!worker.CancellationPending && !_Closing) { // check every second for a signal. if (WaitHandle.WaitAny(waitHandles, 1000) == 0) { // The user tried to start another instance. We can't allow that, // so bring the other instance back into view and enable that one. // That form is created in another thread, so we need some thread sync magic. if (OnAdditionalInstanceSignal != null) OnAdditionalInstanceSignal(sender, new EventArgs()); } } }; singleAppComThread.RunWorkerAsync(); Run(); singleAppComThread.CancelAsync(); while (singleAppComThread.IsBusy) Thread.Sleep(50); threadComEvent.Close(); } finally { if (hasHandle) mutex.ReleaseMutex(); } } }
static void Main(string[] args) { System.Configuration.Install.InstallContext _arg = new System.Configuration.Install.InstallContext(null, args); if (_arg.IsParameterTrue("debug")) { System.Console.WriteLine("Wait for debugger, press any key to continue..."); System.Console.ReadKey(); } // dump version logIt(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileVersionInfo.ToString()); // dump args logIt(string.Format("called by arg: ({0})", args.Length)); foreach (string s in args) { logIt(s); } System.AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); if (_arg.IsParameterTrue("start-service")) { // start service Boolean bFind = false; try { ewait = System.Threading.EventWaitHandle.OpenExisting(IdeviceInfoSvcHost_Event_Name); ewait.Close(); logIt("Instance already started."); } catch (WaitHandleCannotBeOpenedException) { bFind = true; } catch (Exception) { } if (bFind) { try { ewait = new EventWaitHandle(false, EventResetMode.ManualReset, IdeviceInfoSvcHost_Event_Name); //Util.InitEnviroment(); new Thread(() => { iDeviceClass.start(); }).Start(); Console.WriteLine(@"Press any key to terminate..."); while (!ewait.WaitOne(1000)) { if (System.Console.KeyAvailable) { ewait.Set(); } } ewait.Close(); iDeviceClass.stop(); } catch (Exception) { } } } else if (_arg.IsParameterTrue("kill-service")) { // stop service try { ewait = System.Threading.EventWaitHandle.OpenExisting(IdeviceInfoSvcHost_Event_Name); if (ewait != null) { ewait.Set(); } } catch (Exception) { } } else { System.Console.WriteLine("MonitoriDevice.exe"); System.Console.WriteLine("-start-service: to start the service"); System.Console.WriteLine("-kill-service: to stop the service"); } }
void KeyRepeatThread() { var keyRepeatEvent = new EventWaitHandle(false, EventResetMode.AutoReset, repeatEvent); ScanCode repeatingKey = 0; while (keyRepeatRunning) { if (lastKeyPressed != 0) { repeatingKey = lastKeyPressed; Thread.Sleep(300); } if (!keyRepeatRunning) break; while ( lastKeyPressed != 0 && keyRepeatRunning && repeatingKey == lastKeyPressed) { KeyRepeat(repeatingKey); Thread.Sleep(30); } if (!keyRepeatRunning) break; keyRepeatEvent.WaitOne(); } keyRepeatEvent.Close(); var keyRepeatExit = new EventWaitHandle(false, EventResetMode.AutoReset, repeatExit); keyRepeatExit.Set(); keyRepeatExit.Close(); }
private void btnGetStats_Click(object sender, EventArgs e) { if(_active_servo == null) { MsgBox.Show(this, "Select a Node"); return; } // Uncheck 'Show Stored Statistics' radio button suppress_stored_plot_checkbox = true; cbxShowStatsPrev.Checked = false; suppress_stored_plot_checkbox = false; _statistics_ev = new AutoResetEvent(false); Graphics g = picbxStats.CreateGraphics(); try { if(_active_servo.ServoSlave.StatsRead(GetStatistics_callback)) { g.Clear(System.Drawing.Color.White); g.DrawString("Wait for Statistics", new Font("Verdana", 14), new SolidBrush(Color.Black), 10, 10); if(_statistics_ev.WaitOne(15000, false) == false) { MsgBox.Show(this, "Stats timeout\n"); g.Clear(System.Drawing.Color.White); _statistics_ev.Close(); _statistics_ev = null; return; } } } catch(Exception error) { MsgBox.Show(this, error.ToString()); Log(LogMsgType.Error, error.ToString() + "\n"); } _statistics_ev.Close(); _statistics_ev = null; ClrText(tbxStats); if(_active_servo.ServoSlave.StatBuf == null) { MsgBox.Show(this, "StatBuf is null!"); return; } if(_active_servo.ServoSlave.StatBuf.Count > 0) { // We've got valid stats data - copy stats buffer to StatsCur _active_servo.StatsCur = _active_servo.ServoSlave.StatBuf; // Build control points from mem funcs _active_servo.CtlPtsCur.Clear(); if(cbxMemFuncCtlPts.Checked) { // Derive PosErr Ctl points from bytes 4 and 1 of PosMembershipFunctionArray _active_servo.CtlPtsCur.Add(_active_servo.ServoSlave.PosMemFuncArray[4]); _active_servo.CtlPtsCur.Add(_active_servo.ServoSlave.PosMemFuncArray[1]); // Derive Change Ctl points from bytes 4 and 1 of SpdMembershipFunctionArray _active_servo.CtlPtsCur.Add(_active_servo.ServoSlave.SpdMemFuncArray[4]); _active_servo.CtlPtsCur.Add(_active_servo.ServoSlave.SpdMemFuncArray[1]); // Derive Output Ctl points from bytes 0 and 1 of OutSingletonArray _active_servo.CtlPtsCur.Add(_active_servo.ServoSlave.OutSingletonArray[0]); _active_servo.CtlPtsCur.Add(_active_servo.ServoSlave.OutSingletonArray[1]); } else { _active_servo.CtlPtsCur.Clear(); } } else { g.Clear(System.Drawing.Color.White); Log(LogMsgType.Warning, "Statistics Buffer empty - initiate a move to fill\n"); MsgBox.Show(this, "Statistics Buffer empty - initiate a move to fill"); return; } // Build text box output StringBuilder sb = new StringBuilder(); foreach(StatStruct stat in _active_servo.StatsCur) { sb.Append(stat.err.ToString("X2") + " "); sb.Append(stat.change.ToString("X2") + " "); sb.Append(stat.duty.ToString("X2") + "\r\n"); } SetText(tbxStats, sb.ToString()); plotData(_active_servo); g.Dispose(); }
private static void OnClick(object sender, RemoteEventArgs e) { Log.Write("MPTray: OnClick"); switch (e.Button) { case RemoteButton.Start: #region start Process[] processes = Process.GetProcessesByName("mediaportal"); if (processes.Length != 0) { if (processes.Length > 1) { Log.Write("MPTray: More than one process named \"MediaPortal\" has been found!"); foreach (Process procName in processes) { Log.Write("MPTray: {0} (Started: {1}, ID: {2})", procName.ProcessName, procName.StartTime.ToShortTimeString(), procName.Id); } } Log.Write("MPTray: MediaPortal is already running - switching focus."); SwitchFocus(); } else { try { Uri uri = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase); Process process = new Process { StartInfo = { FileName = "mediaportal.exe", WorkingDirectory = Path.GetDirectoryName(uri.LocalPath), UseShellExecute = true } }; Log.Write("MPTray: starting MediaPortal"); process.Start(); using (EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset, "MediaPortalHandleCreated")) { if (handle.SafeWaitHandle.IsInvalid) { return; } SwitchFocus(); handle.Set(); handle.Close(); } } catch (Exception ex) { Log.Write("MPTray: Error starting MediaPortal {0}", ex.Message); } } break; // case RemoteButton.Start #endregion case RemoteButton.Power1: case RemoteButton.Power2: case RemoteButton.PowerTV: #region Power break; // case Remotebutton.Powerxxx #endregion } // switch }
public void TestRepMgr() { testName = "TestRepMgr"; testHome = testFixtureHome + "/" + testName; clientStartSignal = new AutoResetEvent(false); masterCloseSignal = new AutoResetEvent(false); Thread thread1 = new Thread(new ThreadStart(Master)); Thread thread2 = new Thread(new ThreadStart(Client)); // Start master thread before client thread. thread1.Start(); Thread.Sleep(1000); thread2.Start(); thread2.Join(); thread1.Join(); clientStartSignal.Close(); masterCloseSignal.Close(); }
/// <summary> /// This function starts local node when process is launched and shuts it down on time out /// Called by msbuild.exe. /// </summary> public static void StartLocalNodeServer(int nodeNumber) { // Create global events necessary for handshaking with the parent if (!CreateGlobalEvents(nodeNumber)) { return; } LocalNode localNode = new LocalNode(nodeNumber); WaitHandle[] waitHandles = new WaitHandle[4]; waitHandles[0] = shutdownEvent; waitHandles[1] = globalNodeErrorShutdown; waitHandles[2] = inUseEvent; waitHandles[3] = globalInitiateActivationEvent; // This is necessary to make build.exe finish promptly. Dont remove. if (!Engine.debugMode) { // Create null streams for the current input/output/error streams Console.SetOut(new StreamWriter(Stream.Null)); Console.SetError(new StreamWriter(Stream.Null)); Console.SetIn(new StreamReader(Stream.Null)); } bool continueRunning = true; while (continueRunning) { int eventType = WaitHandle.WaitAny(waitHandles, inactivityTimeout, false); if (eventType == 0 || eventType == 1 || eventType == WaitHandle.WaitTimeout) { continueRunning = false; localNode.ShutdownNode(eventType != 1 ? Node.NodeShutdownLevel.PoliteShutdown : Node.NodeShutdownLevel.ErrorShutdown, true, true); } else if (eventType == 2) { // reset the event as we do not want it to go into this state again when we are done with this if statement. inUseEvent.Reset(); // The parent knows at this point the child process has been launched globalNodeActivate.Reset(); // Set the global inuse event so other parent processes know this node is now initialized globalNodeInUse.Set(); // Make a copy of the parents handle to protect ourselves in case the parent dies, // this is to prevent a parent from reserving a node another parent is trying to use. globalNodeReserveHandle = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeReserveEventName(nodeNumber)); WaitHandle[] waitHandlesActive = new WaitHandle[3]; waitHandlesActive[0] = shutdownEvent; waitHandlesActive[1] = globalNodeErrorShutdown; waitHandlesActive[2] = notInUseEvent; eventType = WaitHandle.WaitTimeout; while (eventType == WaitHandle.WaitTimeout && continueRunning == true) { eventType = WaitHandle.WaitAny(waitHandlesActive, parentCheckInterval, false); if (eventType == 0 || /* nice shutdown due to shutdownEvent */ eventType == 1 || /* error shutdown due to globalNodeErrorShutdown */ eventType == WaitHandle.WaitTimeout && !localNode.IsParentProcessAlive()) { continueRunning = false; // If the exit is not triggered by running of shutdown method if (eventType != 0) { localNode.ShutdownNode(Node.NodeShutdownLevel.ErrorShutdown, true, true); } } else if (eventType == 2) { // Trigger a collection before the node goes idle to insure that // the memory is released to the system as soon as possible GC.Collect(); // Change the current directory to a safe one so that the directory // last used by the build can be safely deleted. We must have read // access to the safe directory so use SystemDirectory for this purpose. Directory.SetCurrentDirectory(Environment.SystemDirectory); notInUseEvent.Reset(); globalNodeInUse.Reset(); } } ErrorUtilities.VerifyThrow(localNode.node == null, "Expected either node to be null or continueRunning to be false."); // Stop the communication threads and release the shared memory object so that the next parent can create it localNode.StopCommunicationThreads(); // Close the local copy of the reservation handle (this allows another parent to reserve // the node) globalNodeReserveHandle.Close(); globalNodeReserveHandle = null; } else if (eventType == 3) { globalInitiateActivationEvent.Reset(); localNode.StartCommunicationThreads(); globalNodeActivate.Set(); } } // Stop the communication threads and release the shared memory object so that the next parent can create it localNode.StopCommunicationThreads(); globalNodeActive.Close(); globalNodeInUse.Close(); }
void ReadThread() { DeviceData data; while (runReadThread) { try { if (!IsOpen) PollForConnect(); if (!runReadThread) break; data = ReadData(readDataTimeout); switch (data.Status) { case DeviceData.ReadStatus.Cancelled: ReadThread_Cancelled(); break; case DeviceData.ReadStatus.WaitTimedOut: ReadThread_WaitTimedOut(); break; case DeviceData.ReadStatus.Success: bool dataRead = false; for (int i = 0; i < data.Bytes.Length; i++) { if (data.Bytes[i] != 0) { dataRead = true; break; } } if (dataRead) ReadThread_DataRead(data); else ReadThread_NoDataRead(); break; case DeviceData.ReadStatus.ReadError: ReadThread_ReadError(data.Error); break; case DeviceData.ReadStatus.NoDataRead: ReadThread_NoDataRead(); break; } } catch (Exception ex) { ReadThread_ReadError(ex); } } var readExit = new EventWaitHandle(false, EventResetMode.AutoReset, readExitName); readExit.Set(); readExit.Close(); }
protected virtual void WriteThread() { var localWriteEvent = new EventWaitHandle(false, EventResetMode.AutoReset, writeEventName); while (runWriteThread) { if (IsConnected) { lock (writeDelegates) { using (var safe = new SafeFileHandle(OpenDeviceIO(DeviceInfo.Path, DeviceMode.NonOverlapped, NativeMethods.GENERIC_WRITE), true)) { var writeDelegateLink = writeDelegates.First; var next = writeDelegateLink; while (writeDelegateLink != null) { if (!IsConnected || !runWriteThread) break; next = writeDelegateLink.Next; if (WriteType.Complete == writeDelegateLink.Value(this, safe)) writeDelegates.Remove(writeDelegateLink); writeDelegateLink = next; } } } if (runWriteThread) { if (writeDelegates.Count == 0) localWriteEvent.WaitOne(); else Thread.Sleep(DelayBetweenWrites); } } else localWriteEvent.WaitOne(); } localWriteEvent.Close(); var writeExit = new EventWaitHandle(false, EventResetMode.AutoReset, writeExitName); writeExit.Set(); writeExit.Close(); }
//-------------------------------------------------------------------------- // Data Reception //-------------------------------------------------------------------------- // http://www.beefycode.com/post/Using-Overlapped-IO-from-Managed-Code.aspx #pragma warning disable 0618 // warning CS0618: 'System.Threading.WaitHandle.Handle' is obsolete: 'Use the SafeWaitHandle property instead.' unsafe void ReadThread(ThreadContext ctx) { System.Threading.Thread.CurrentThread.Name = "USBConnection.ReadThread"; EventWaitHandle asyncReadCompleteEvent = new EventWaitHandle(false, System.Threading.EventResetMode.ManualReset); NativeOverlapped* pNativeOverlapped = null; byte[] rgbBuffer = new byte[64]; try { WaitHandle[] waitHandles = new WaitHandle[2]; waitHandles[0] = asyncReadCompleteEvent; waitHandles[1] = ctx.StopEvent; // // If we get unexpected errors, we stop reading; likely these are caused by a device // in the process of disconnecting. // bool fStop = false; // while (!fStop && !ctx.StopRequest) { // Issue an async read // asyncReadCompleteEvent.Reset(); Overlapped overlapped = new Overlapped(0, 0, asyncReadCompleteEvent.Handle, null); pNativeOverlapped = overlapped.Pack(null, rgbBuffer); int cbRead = 0; // Program.Trace("issuing async read: 0x{0:08X} 0x{1:08X}", new IntPtr(pNativeOverlappedWrite), this.hWinUSB); bool fSuccess = WinUsb_ReadPipe( this.hWinUSB, bulkInPipe, rgbBuffer, rgbBuffer.Length, out cbRead, new IntPtr(pNativeOverlapped)); this.readThreadRunning.Set(); if (!fSuccess) { int err = Marshal.GetLastWin32Error(); if (err != ERROR_IO_PENDING) { Program.Trace("USB Read: WinUsb_ReadPipe=={0}", err); fStop = true; continue; } } // Wait until either the async read completes or we're asked to stop int iWait = WaitHandle.WaitAny(waitHandles); // Process according to which event fired switch (iWait) { case 0: // Async read completed { // Program.Trace("async read complete: 0x{0:08X} 0x{1:08X}", new IntPtr(pNativeOverlappedWrite), this.hWinUSB); if (WinUsb_GetOverlappedResult(this.hWinUSB, new IntPtr(pNativeOverlapped), ref cbRead, System.Convert.ToByte(true))) { ProcessIncomingPacket(rgbBuffer, cbRead); } else { int err = Marshal.GetLastWin32Error(); Program.Trace("USB Read: WinUsb_GetOverlappedResult=={0}", err); fStop = true; } // System.Threading.Overlapped.Free(pNativeOverlapped); pNativeOverlapped = null; } break; case 1: // StopEvent // Program.Trace("async read stop requested"); break; // end switch } } } finally { // Program.Trace("async cleanup: 0x{0:08X} 0x{1:08X}", new IntPtr(pNativeOverlappedWrite), this.hWinUSB); WinUsb_AbortPipe(this.hWinUSB, bulkInPipe); asyncReadCompleteEvent.Close(); if (pNativeOverlapped != null) { System.Threading.Overlapped.Free(pNativeOverlapped); pNativeOverlapped = null; } } }
/// <summary> /// This function attempts to find out a node number for which /// the event named Node_x_ProviderMutex doesn't exist. The existance /// of the event indicates that some other node provider is using the node. /// </summary> private void ReserveNextAvailableNodeNumber(int currentNodeNumber) { while (nodeReserveHandle == null) { bool createdNew = false; nodeReserveHandle = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeReserveEventName(currentNodeNumber), out createdNew); if (!createdNew) { nodeReserveHandle.Close(); nodeReserveHandle = null; currentNodeNumber++; } else { nodeNumber = currentNodeNumber; // Create the shared memory resources if (!CreateSharedMemoryBuffers()) { nodeReserveHandle.Close(); nodeReserveHandle = null; currentNodeNumber++; } } } }
static void Main(string[] args) { System.Configuration.Install.InstallContext _arg = new System.Configuration.Install.InstallContext(null, args); if (_arg.IsParameterTrue("debug")) { System.Console.WriteLine("Wait for debugger, press any key to continue..."); System.Console.ReadKey(); } // dump version logIt(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileVersionInfo.ToString()); // dump args logIt(string.Format("called by arg: ({0})", args.Length)); foreach (string s in args) { logIt(s); } IniFile ini = new IniFile(Path.Combine(Environment.ExpandEnvironmentVariables(@"%APSTHOME%"), "config.ini")); String sMaxcapacity = ini.GetString("battery", "read_ratio_reboot", "false"); Util.IsMaxCapacity = String.Compare(sMaxcapacity, "true", true) == 0 || String.Compare(sMaxcapacity, "1", true) == 0; //Util.IsMaxCapacity = true; logIt($"config Maxcapacity = {sMaxcapacity}:{Util.IsMaxCapacity}"); System.AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); if (_arg.IsParameterTrue("start-service")) { // start service Boolean bRun = false; try { ewait = System.Threading.EventWaitHandle.OpenExisting(IdeviceInfoSvcHost_Event_Name); ewait.Close(); logIt("Instance already started."); } catch (WaitHandleCannotBeOpenedException) { bRun = true; } catch (Exception) { } if (bRun) { try { ewait = new EventWaitHandle(false, EventResetMode.ManualReset, IdeviceInfoSvcHost_Event_Name); //Util.InitEnviroment(); ThreadPool.QueueUserWorkItem(new WaitCallback(Util.runMonitorExe), null); using (ServiceHost host = new ServiceHost(typeof(Device))) { host.Open(); Console.WriteLine(@"go to http://localhost:1930/device to test"); Console.WriteLine(@"Press any key to terminate..."); while (!ewait.WaitOne(1000)) { if (System.Console.KeyAvailable) { ewait.Set(); } } host.Close(); } Util.bExit = true; Util.runMonitorExe("-kill-service"); ewait.Close(); } catch (Exception) { logIt("iTunes MobileDevice.Dll not found.************"); } Util.bExit = true; Util.runMonitorExe("-kill-service"); ewait.Close(); } } else if (_arg.IsParameterTrue("kill-service")) { // stop service try { ewait = System.Threading.EventWaitHandle.OpenExisting(IdeviceInfoSvcHost_Event_Name); if (ewait != null) { ewait.Set(); } } catch (Exception) { } } else { System.Console.WriteLine("IdeviceInfoSvcHost.exe"); System.Console.WriteLine("-start-service: to start the service"); System.Console.WriteLine("-kill-service: to stop the service"); } }
private void listenUsingNamedEventsAndMemoryMappedFiles() { if (m_NamedEventHandle == null) { EventLog.WriteEntry("Application", string.Format( "IpcService::listenUsingNamedEventsAndMemoryMappedFiles: NULL event"), EventLogEntryType.Error); return; } if (m_NamedEventBuddyHandle == null) { EventLog.WriteEntry("IpcService", string.Format("IpcService::listenUsingNamedEventsAndMemoryMappedFiles: NULL event (Buddy)"), EventLogEntryType.Error); return; } m_Terminated = new EventWaitHandle(false, EventResetMode.ManualReset); EventWaitHandle[] waitObjects = new EventWaitHandle[] { m_Terminated, m_NamedEventHandle }; try { while(true) { //Waits on "Ready to read?" int index = EventWaitHandle.WaitAny(waitObjects, Timeout.Infinite,false); if (index == 0) { break; } try { //Read data string data = Peek(); if (IpcEvent != null) { IpcEvent(this, new TextualEventArgs(data)); } } catch(Exception ex) { EventLog.WriteEntry("IpcService", string.Format("IpcService::listenUsingNamedEventsAndMemoryMappedFiles: Error: {0}", ex), EventLogEntryType.Error); } finally { m_NamedEventHandle.Reset(); //Signals "Read done" m_NamedEventBuddyHandle.Set(); } } } finally { if (m_NamedEventHandle != null) { m_NamedEventHandle.Set(); m_NamedEventHandle.Close(); } if (m_NamedEventBuddyHandle != null) { m_NamedEventBuddyHandle.Set(); m_NamedEventBuddyHandle.Close(); } m_Terminated.Close(); } }
/// <summary> /// Creates a new AutoResetEvent using the random number generator. /// </summary> static EventWaitHandle CreateNew(ref int eventName, bool initialValue) { if (rnd == null) rnd = new Random(); EventWaitHandle ev = null; while (ev == null) { eventName = rnd.Next(); bool createdNew; ev = new EventWaitHandle(initialValue, EventResetMode.AutoReset, GetEventName(eventName), out createdNew); if (!createdNew) { Debug.WriteLine("Collision on name creation"); ev.Close(); ev = null; } } return ev; }
/// <summary> /// This function establishes communication with a node given an index. If a node /// is not running it is launched. /// </summary> private void InitializeNode(int nodeIndex) { bool nodeConnected = false; int restartCount = 0; try { IncreaseActiveNodeCount(); while (!nodeConnected && restartCount < maximumNodeRestartCount) { if (!checkIfNodeActive(nodeData[nodeIndex].NodeNumber)) { // Attempt to launch a new node process LaunchNode(nodeIndex); // If we could not launch the node there is no reason to continue if (nodeData[nodeIndex].CommunicationFailed) { break; } } if (checkIfNodeActive(nodeData[nodeIndex].NodeNumber)) { nodeData[nodeIndex].SharedMemoryToNode.Reset(); nodeData[nodeIndex].SharedMemoryFromNode.Reset(); // Activate the initiation event to prove to the child that we have the same level of privilege as it does. This operation will not fail because each privilege level creates // events in different namespaces EventWaitHandle nodeInitiateActivationEvent = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeInitiateActivationEventName(nodeData[nodeIndex].NodeNumber)); nodeInitiateActivationEvent.Set(); nodeInitiateActivationEvent.Close(); // Wait for node to indicate that it is activated EventWaitHandle nodeActivatedEvent = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeActivedEventName(nodeData[nodeIndex].NodeNumber)); nodeActivatedEvent.WaitOne(initializationTimeout, false); nodeActivatedEvent.Close(); // Looked in Environment.cs the IDictionary is a HashTable IDictionary variableDictionary = Environment.GetEnvironmentVariables(); Hashtable environmentVariablesTable = new Hashtable(variableDictionary); LocalCallDescriptorForInitializeNode callDescriptorInit = new LocalCallDescriptorForInitializeNode(environmentVariablesTable, nodeLoggers.ToArray(), nodeData[nodeIndex].NodeId, parentGlobalProperties, toolsetSearchLocations, Process.GetCurrentProcess().Id, startupDirectory); nodeData[nodeIndex].NodeCommandQueue.Enqueue(callDescriptorInit); EventWaitHandle nodeInUseEvent = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeInUseEventName(nodeData[nodeIndex].NodeNumber)); // Wait for node to indicate that it is ready. The node may time out and exit, between // when we check that it is active and before the initialization messages reaches it. // In that rare case we have to restart the node. if (nodeInUseEvent.WaitOne(initializationTimeout, false)) { UpdateSettings(nodeIndex); nodeConnected = true; } nodeInUseEvent.Close(); // If the node is still active and has not replied to the initialization message it must // be in bad state - try to get that node to exit if (!nodeConnected && checkIfNodeActive(nodeData[nodeIndex].NodeNumber)) { EventWaitHandle nodeShutdownEvent = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeErrorShutdownEventName(nodeData[nodeIndex].NodeNumber)); nodeShutdownEvent.Set(); nodeShutdownEvent.Close(); restartCount = maximumNodeRestartCount; } restartCount++; } } } finally { // Make sure to decrement the active node count if the communication has failed if (nodeConnected != true) { DecreaseActiveNodeCount(nodeData[nodeIndex].NodeId); nodeData[nodeIndex].CommunicationFailed = true; } } }