private static void WaiterMethod()
 {
     ColorConsole.WriteWarning("Waiting for auto-reset event signal. Thread ID :" + Thread.CurrentThread.ManagedThreadId);
     _autoResetEvent.WaitOne();
     ColorConsole.WriteInfo("Done.");
     _autoResetEvent.Close();
 }
Exemple #2
0
 /// <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++;
             }
         }
     }
 }
Exemple #3
0
        public void Stop()
        {
            if (!keyRepeatRunning)
            {
                return;
            }

            lastKeyPressed   = 0;
            keyRepeatRunning = false;
            keyRepeatEvent.Set();
            keyRepeatEvent.Close();

            if (Thread.CurrentThread != keyRepeatThread)
            {
                if (!keyRepeatExit.WaitOne(1000))
                {
                    System.Diagnostics.Debug.WriteLine("KeyRepeater.Stop: keyRepeatStop timed out");
                    keyRepeatThread.Abort();
                }
            }

            keyRepeatExit.Close();

            keyRepeatThread = null;
        }
 //--------
 void IBluesoleilConnection.CloseNetworkOrInternal()
 {
     _state = State.PeerDidClose;
     //Debug.Assert(base.CanRead, "CanRead before");
     //Debug.Assert(base.CanWrite, "CanWrite before");
     //_port.Close();
     //Debug.Assert(!base.CanRead, "CanRead after");
     //Debug.Assert(!base.CanWrite, "CanWrite after");
     // Unblock any Reader.
     _received.Set();
     _received.Close();
     _hConn = null;
 }
        /// <summary>
        /// Stops the listener
        /// </summary>
        private void StopEventListener()
        {
            try
            {
                if (eventListenerService != null)
                {
                    RemotingServices.Unmarshal(eventListenerService);
                }

                if (eventInvocation != null)
                {
                    RemotingServices.Disconnect(eventInvocation);
                }

                if (eventListenerChannel != null)
                {
                    ChannelServices.UnregisterChannel(eventListenerChannel);
                }

                if (eventQueue != null)
                {
                    eventQueue.Clear();
                    eventQueue = null;
                }
                if (eventTrigger != null)
                {
                    eventTrigger.Close();
                    eventTrigger = null;
                }
                if (eventProcessor != null)
                {
                    try
                    {
                        if (eventProcessor.IsAlive)
                        {
                            eventProcessor.Abort();
                        }
                    }
                    catch (Exception) { }
                    eventProcessor = null;
                }
                eventListenerService = null;
                eventInvocation      = null;
                eventListenerChannel = null;
            }
            catch (Exception ex)
            {
                log.Error("Error stopping event listener: " + ex.Message, ex);
            }
        }
Exemple #6
0
        public void Dispose()
        {
            if (!m_bCancelling)
            {
                EnqueueFrame(null);                     // Signal the consumer to exit.
                m_WorkerThread.Join();                  // Wait for the consumer's thread to finish.
                m_WaitHandle.Close();                   // Release any OS resources.

                if (m_bInitialized)
                {
                    m_VideoFileWriter.CloseSavingContext(true);
                }
            }
        }
        private async void MainWindowShow(object obj)
        {
            ILogin temp_obj = obj as ILogin;

            if (temp_obj == null)
            {
                return;
            }
            LoadVisible = true;
            _waitHandle = new AutoResetEvent(false);
            await Task.Run(() =>
            {
                foreach (var item in _model.db.StaffSet)
                {
                    if (item.login == Login && (item.password == temp_obj.GetPassword() || item.password == hashing.HashPassword(temp_obj.GetPassword())))
                    {
                        Cur_session.New_session(item.Staff_PosId, item.login, item.password, item.FirstName, item.LastName, item.Staff_Pos.Position, item.phone_number);
                        _waitHandle.Set();

                        break;
                    }
                }
                _waitHandle.Set();
            });

            _waitHandle.WaitOne();
            if (Cur_session.Id == -1)
            {
                WpfMessageBox.Show("Ошибка авторизации", "Пользователь с таким логином или паролем не найден.", 0, MessageBoxImage.Warning);
                LoadVisible = false;
                return;
            }
            if (Cur_session.Id == 1)
            {
                LoadVisible = false;
                _waitHandle.Close();
                AdminWnd adminWnd = new AdminWnd();
                adminWnd.Show();
                temp_obj.Close();
            }
            if (Cur_session.Id == 3)
            {
                LoadVisible = false;
                _waitHandle.Close();
                WaiterWnd waiterWnd = new WaiterWnd();
                waiterWnd.Show();
                temp_obj.Close();
            }
        }
 void IDisposable.Dispose()
 {
     outputStreamClosed.Close();
     errorStreamClosed.Close();
     processExited.Close();
     process.Dispose();
 }
Exemple #9
0
 public void kill()
 {
     isPendingClose = true;
     waitHandleBetweenTasks.Set();
     thread.Join();
     waitHandleBetweenTasks.Close();
 }
Exemple #10
0
 public void Dispose()
 {
     // Signal the end by sending 'null'
     EnqueuexmlEvent(null);
     xmlProcessingThread.Join();
     _whxmlEvent.Close();
 }
Exemple #11
0
        private void BgCancelTrace_DoWork(object sender, DoWorkEventArgs e)
        {
            EventWaitHandle doneWithInit = new EventWaitHandle(false, EventResetMode.ManualReset, "ASProfilerTraceImporterCmdCancelSignal");

            doneWithInit.Set();
            ASProfilerTraceImporterProcess.WaitForExit();
            connSqlDb.ChangeDatabase("master");
            doneWithInit.Close();
            SqlCommand cmd = new SqlCommand("IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'" + AnalysisTraceID + "') ALTER DATABASE [" + AnalysisTraceID + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE", connSqlDb);

            cmd.ExecuteNonQuery();
            cmd = new SqlCommand("IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'" + AnalysisTraceID + "') DROP DATABASE [" + AnalysisTraceID + "]", connSqlDb);
            cmd.ExecuteNonQuery();
            connSqlDb.Close();
            if (m_analysisPath.EndsWith(".mdf"))
            {
                File.Delete(m_analysisPath);
                File.Delete(m_analysisPath.Replace(".mdf", ".ldf"));
            }
            else
            {
                File.Delete(m_analysisPath + "\\Analysis\\" + AnalysisTraceID + ".mdf");
                File.Delete(m_analysisPath + "\\Analysis\\" + AnalysisTraceID + ".ldf");
            }
        }
Exemple #12
0
#pragma warning disable CS8618 // Non-nullable property is uninitialized
        public App()
        {
            // Ensure only one instance is running at a time.
            App.AddLog("Checking uniqueness");
            try
            {
                bool createdNew;
                InstanceEvent = new EventWaitHandle(false, EventResetMode.ManualReset, "{5293D078-E9B9-4E5D-AD4C-489A017748A5}", out createdNew);
                if (!createdNew)
                {
                    App.AddLog("Another instance is already running");
                    InstanceEvent.Close();
                    InstanceEvent = null;
                    Shutdown();
                    return;
                }
            }
            catch (Exception e)
            {
                App.AddLog($"(from App) {e.Message}");

                Shutdown();
                return;
            }

            Startup     += OnStartup;
            ShutdownMode = ShutdownMode.OnExplicitShutdown;
        }
        public override void Close()
        {
            if (connectionClosed != null)
            {
                bool isClosed = connectionClosed.WaitOne(0);
                if (!isClosed)
                {
                    connectionClosed.Set();
                    connectionClosed.Close();
                }
                connectionClosed = null;
                EventWaitHandle[] handles = { serverRead, serverWrote, clientRead, clientWrote };

                for (int i = 0; i < handles.Length; i++)
                {
                    if (handles[i] != null)
                    {
                        handles[i].Close();
                    }
                }
                if (data != null)
                {
                    data.Dispose();
                    data = null;
                }
            }
        }
Exemple #14
0
        // set exit event so that openvpn will terminate
        public void SignalProcess()
        {
            if (restartTimer != null)
            {
                restartTimer.Stop();
            }
            try
            {
                if (!process.HasExited)
                {
                    try {
                        var waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, exitEvent);

                        process.Exited -= Watchdog; // Don't restart the process after exit

                        waitHandle.Set();
                        waitHandle.Close();
                    } catch (IOException e) {
                        config.eventLog.WriteEntry("IOException creating exit event named '" + exitEvent + "' " + e.Message + e.StackTrace);
                    } catch (UnauthorizedAccessException e) {
                        config.eventLog.WriteEntry("UnauthorizedAccessException creating exit event named '" + exitEvent + "' " + e.Message + e.StackTrace);
                    } catch (WaitHandleCannotBeOpenedException e) {
                        config.eventLog.WriteEntry("WaitHandleCannotBeOpenedException creating exit event named '" + exitEvent + "' " + e.Message + e.StackTrace);
                    } catch (ArgumentException e) {
                        config.eventLog.WriteEntry("ArgumentException creating exit event named '" + exitEvent + "' " + e.Message + e.StackTrace);
                    }
                }
            }
            catch (InvalidOperationException) { }
        }
        static void Main(string[] args)
        {
            EventWaitHandle ewh = null;

            try
            {
                ewh = new EventWaitHandle(false, EventResetMode.AutoReset, "CHILD_PROCESS_READY");

                Process process = Process.Start("MyChildProcess.exe", Process.GetCurrentProcess().Id.ToString());
                if (process != null)
                {
                    if (ewh.WaitOne(10000))
                    {
                        // Child process is ready.
                    }
                }
            }
            catch (Exception exception)
            { }
            finally
            {
                if (ewh != null)
                {
                    ewh.Close();
                }
            }
        }
Exemple #16
0
 public void Dispose()
 {
     EnqueueTask(null);     // Signal the consumer to exit.
     _worker.Join();        // Wait for the consumer's thread to finish.
     _wh.Close();           // Release any OS resources.
     Console.WriteLine("对象销毁完毕...");
 }
Exemple #17
0
 /// <summary>
 /// 安装更新。
 /// </summary>
 public void InstallUpdate()
 {
     if (!IsNeedToBeUpdated)
     {
         return;
     }
     if (Args.ProcessId > 0)
     {
         Process process = Process.GetProcessById(Args.ProcessId);
         if (process != null)
         {
             EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, Args.SoftwareGuid);
             NativeMethods.PostThreadMessage(process.Threads[0].Id, NativeMethods.WM_APP_UPDATE, Marshal.StringToHGlobalAuto(Args.SoftwareGuid), Marshal.GetFunctionPointerForDelegate(new Action(() => eventWaitHandle.Set())));
             eventWaitHandle.WaitOne(60000);
             eventWaitHandle.Close();
         }
     }
     else if (!string.IsNullOrEmpty(Args.ClassName))
     {
         IntPtr hWnd = NativeMethods.FindWindow(Args.ClassName, null);
         while (hWnd != IntPtr.Zero)
         {
             NativeMethods.SendMessage(hWnd, NativeMethods.WM_CLOSE, (IntPtr)NativeMethods.WM_APP_UPDATE, IntPtr.Zero);
             hWnd = NativeMethods.FindWindow(Args.ClassName, null);
         }
     }
     Process.Start(UpdatePackageName, string.Format(Args.Arguments, Args.SoftwareName, Args.SoftwareGuid, Args.CurrentVersion, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)));
 }
Exemple #18
0
 protected override void OnStop()
 {
     _stopping = true;
     _serviceEvent.Set();
     _barbaComm.Stop();
     _serviceEvent.Close();
 }
Exemple #19
0
        public void TestRepMgr()
        {
            testName = "TestRepMgr";
            SetUpTest(true);

            // Initialize ports for master and client.
            ports.Clear();
            AvailablePorts portGen = new AvailablePorts();

            ports.Insert(0, portGen.Current);
            portGen.MoveNext();
            ports.Insert(1, portGen.Current);

            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();
        }
Exemple #20
0
 public void Dispose()
 {
     KillWorker();
     _Worker.Join();
     _EventWaitHandle.Close();
     GC.SuppressFinalize(this);
 }
Exemple #21
0
 public void Close()
 {
     mtx.Close();
     evt.Close();
     Win32.UnmapViewOfFile(dataptr);
     Win32.CloseHandle(hmmf);
 }
Exemple #22
0
 public void Dispose()
 {
     DisposeMusic();
     DisposeSound();
     musicHandle.Close();
     game.UserEvents.BlockChanged -= PlayBlockSound;
 }
Exemple #23
0
 public void Dispose()
 {
     // Signal the end by sending 'null'
     EnqueueSensorEvent(null);
     sensorProcessingThread.Join();
     _whSensorEvent.Close();
 }
Exemple #24
0
 static void Waiter()
 {
     Console.WriteLine("Waiting in Waiter method called from worker thread...");
     _waitHandle.WaitOne();
     _waitHandle.Close();
     Console.WriteLine("Completed Waiting in Waiter method called from worker thread...");
 }
Exemple #25
0
        /// <summary>
        /// IDispose satisfaction
        /// </summary>
        public virtual void Dispose()
        {
            try
            {
                logger.Debug(string.Format("Disposing {0} ... ", threadName));

                if (samplesQ != null)
                {
                    samplesQ.Clear();
                }
                qEvent.Close();
                evtTerminate.Close();
                qEvent       = null;
                evtTerminate = null;
                eventHandles = null;
                if (udp != null)
                {
                    udp.Close();
                }
            }
            catch (Exception e)
            {
                logger.Exception(e);
            }
        }
Exemple #26
0
 protected override void OnUnManagedDispose()
 {
     if (!m_Handle.SafeWaitHandle.IsClosed)
     {
         m_Handle.Close();
     }
 }
Exemple #27
0
        protected void StopWrite()
        {
            if (!runWriteThread)
            {
                return;
            }

            runWriteThread = false;

            lock (writeDelegates)
            {
                writeDelegates.Clear();
            }

            writeEvent.Set();
            writeEvent.Close();

            if (Thread.CurrentThread != writeThread)
            {
                if (!writeExit.WaitOne(1000))
                {
                    System.Diagnostics.Debug.WriteLine("StopWrite: writeExit.WaitOne timed out");
                    writeThread.Abort();
                }
            }

            writeExit.Close();

            writeThread = null;
        }
Exemple #28
0
        /// <summary>
        /// Stops receiving of the data.
        /// </summary>
        public void Close()
        {
            if (threadProcessing != null)
            {
                isRunning = false;
                eventDataReady.Set();

                // wait for thread to finish:
                if (threadProcessing != null)
                {
                    threadProcessing.Join(3000);
                }

                threadProcessing = null;
            }

            if (eventBufferReady != null)
            {
                eventBufferReady.Close();
                eventBufferReady = null;
            }

            if (eventDataReady != null)
            {
                eventDataReady.Close();
                eventDataReady = null;
            }

            if (sharedMemory != null)
            {
                sharedMemory.Close();
                sharedMemory = null;
            }
        }
        protected void Close()
        {
            if (_notifyEvent != null)
            {
                _notifyEvent.Close();
                _notifyEvent.Dispose();
                _notifyEvent = null;
            }

            if (_mutex != null)
            {
                _mutex.Close();
                _mutex.Dispose();
                _mutex = null;
            }
            if (_stream != null)
            {
                _stream.Close();
                _stream = null;
            }
            if (_memMappedFile != null)
            {
                _memMappedFile.Dispose();
                _memMappedFile = null;
            }
        }
        public override bool Execute()
        {
            bool ret = ExecuteCore();

            cancelEvent.Close();
            return(ret);
        }