当前位置: 首页>>代码示例>>C#>>正文


C# EventWaitHandle.Close方法代码示例

本文整理汇总了C#中System.Threading.EventWaitHandle.Close方法的典型用法代码示例。如果您正苦于以下问题:C# EventWaitHandle.Close方法的具体用法?C# EventWaitHandle.Close怎么用?C# EventWaitHandle.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Threading.EventWaitHandle的用法示例。


在下文中一共展示了EventWaitHandle.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ForceOnce

    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;
    }
开发者ID:astalavister,项目名称:IR-Server-Suite,代码行数:31,代码来源:FocusForcer.cs

示例2: IsFirstInstance

    /// <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;
    }
开发者ID:cornelius90,项目名称:InnovatorAdmin,代码行数:35,代码来源:SingleInstance.cs

示例3: Main

        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();
        }
开发者ID:SonicFreak94,项目名称:DS4Windows,代码行数:51,代码来源:Program.cs

示例4: CreateSingleInstance

        /// <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;
        }
开发者ID:abibell,项目名称:mysql-workbench,代码行数:55,代码来源:ApplicationInstanceManager.cs

示例5: Make

        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);
            }
        }
开发者ID:gahadzikwa,项目名称:GAPP,代码行数:46,代码来源:WpfSingleInstance.cs

示例6: CreateSingleInstance

		/// <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;
		}
开发者ID:rad1oactive,项目名称:BetterExplorer,代码行数:52,代码来源:ApplicationInstanceManager.cs

示例7: CheckForOtherApp

        /// <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;
        }
开发者ID:khaikin,项目名称:GymMgr,代码行数:25,代码来源:SingleInstCode.cs

示例8: ActivatorHost

        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();
                }
            }
        }
开发者ID:legendary-code,项目名称:process-domain,代码行数:38,代码来源:ActivatorHost.cs

示例9: TestElection

        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();
        }
开发者ID:gildafnai82,项目名称:craq,代码行数:41,代码来源:ReplicationTest.cs

示例10: btnGetStats_Click

        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();
        }
开发者ID:robmilne,项目名称:viTestApp,代码行数:96,代码来源:MainForm.Statistics.cs

示例11: RunThread

        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();
        }
开发者ID:HaKDMoDz,项目名称:GNet,代码行数:49,代码来源:G13ProfileRunner.cs

示例12: CreateAddInProcess

        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;
        }
开发者ID:JianwenSun,项目名称:cc,代码行数:48,代码来源:AddInProcess.cs

示例13: CreateSubmitWorkerThread

        // 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();
        }
开发者ID:killbug2004,项目名称:WSProf,代码行数:30,代码来源:OutboxMonitor.cs

示例14: listenUsingNamedEventsAndMemoryMappedFiles

        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();
            }
        }
开发者ID:dbose,项目名称:QuickIPC,代码行数:76,代码来源:QuickIPC.cs

示例15: ReserveNextAvailableNodeNumber

        /// <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++;
                    }

                }
            }
        }
开发者ID:nikson,项目名称:msbuild,代码行数:32,代码来源:LocalNodeInfo.cs


注:本文中的System.Threading.EventWaitHandle.Close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。