public void Dispose() { if (_wh != null) { _wh.Dispose(); } }
protected virtual void Dispose(bool disposing) { if (disposed) { return; } // Always set the dispose wait handle even when dispised by the finalizer // otherwize the file watcher task will needleessly have to wait for its timeout. disposeWaitHandle?.Set(); fileWatcherTask?.Wait(TinyReadWriteLock.DefaultWaitTimeout); if (disposing) { memoryMappedFile.Dispose(); if (disposeLock && readWriteLock is IDisposable disposableLock) { disposableLock.Dispose(); } fileWaitHandle.Dispose(); disposeWaitHandle?.Dispose(); } disposed = true; }
public void Dispose() { view.Dispose(); file.Dispose(); requestReadyEvent?.Dispose(); replyReadyEvent?.Dispose(); }
public void Dispose() { EventWaitHandle.Dispose(); _cts.Dispose(); GC.SuppressFinalize(this); }
private void ConsumerThreadStart() { while (true) { if (m_shutDown.WaitOne(0)) { break; } if (!m_events.HeadValidEvent.WaitOne(25)) { continue; } while (!m_events.IsEmpty) { if (m_shutDown.WaitOne(0)) { break; } FileSystemEventArgs e = m_events.Dequeue(); ProcessEvent(e); } } m_shutDown.Close(); m_shutDown.Dispose(); }
/// <inheritdoc/> public bool Stop() { if (!_started) { // TODO check if started // throw Exception } bool succes = true; try{ _logger?.LogTrace(LoggingEvents.C2E_CLOSE_CONNECTION, "Injector {0} Stop", Game); requestEventHandle.Dispose(); resultEventHandle.Dispose(); memViewAccessor.Dispose(); memfile.Dispose(); mutex.Dispose(); } catch (System.NullReferenceException ex) { _logger?.LogWarning(LoggingEvents.C2E_CLOSE_CONNECTION, ex, "Shared Memory fail on Stop: {0}", Game); succes = false; } finally { _logger?.LogInformation(LoggingEvents.C2E_CLOSE_CONNECTION, "Injector {0} Stop : {1}", Game, succes); } return(succes); }
/// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (!_isDisposed) { base.Dispose(disposing); if (disposing) { if (Session != null) { Session.RequestSuccessReceived -= Session_RequestSuccess; Session.RequestFailureReceived -= Session_RequestFailure; Session.ChannelOpenReceived -= Session_ChannelOpening; Session = null; } if (_globalRequestResponse != null) { _globalRequestResponse.Dispose(); _globalRequestResponse = null; } } _isDisposed = true; } }
private void Channel_Closed(object sender, ChannelEventArgs e) { if (Stopping != null) { // Handle event on different thread ThreadAbstraction.ExecuteThread(() => Stopping(this, new EventArgs())); } _channel.Dispose(); _channelClosedWaitHandle.Set(); _input.Dispose(); _input = null; _dataReaderTaskCompleted.WaitOne(_session.ConnectionInfo.Timeout); _dataReaderTaskCompleted.Dispose(); _dataReaderTaskCompleted = null; _channel.DataReceived -= Channel_DataReceived; _channel.ExtendedDataReceived -= Channel_ExtendedDataReceived; _channel.Closed -= Channel_Closed; UnsubscribeFromSessionEvents(_session); if (Stopped != null) { // Handle event on different thread ThreadAbstraction.ExecuteThread(() => Stopped(this, new EventArgs())); } _channel = null; }
/// <summary> /// Tuät ä nii Inschantz vom virtueuä DMD kreiärä und tuät drnah d /// Render-Graphä drabindä. /// </summary> private void CreateVirtualDmd() { // set up an event object to synchronize with the thread startup var ev = new EventWaitHandle(false, EventResetMode.AutoReset); // launch a thrtead for the virtual DMD window event handler var thread = new Thread(() => { // create the virtual DMD window and create the render grahps _dmd = new VirtualDmd(); //---_alphaNumericDisplay = new VirtualAlphaNumericDisplay(); SetupGraphs(); // Create our context, and install it: SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher)); // When the window closes, shut down the dispatcher _dmd.Closed += (s, e) => _dmd.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Background); _dmd.Dispatcher.Invoke(SetupVirtualDmd); // we're done with the setup - let the calling thread proceed ev.Set(); // Start the Dispatcher Processing Dispatcher.Run(); }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); // wait until the virtual DMD window is fully set up, to avoid any // race conditions with the UI thread ev.WaitOne(); ev.Dispose(); }
/// <summary> /// освободить системные ресурсы, использованные для управления блокировками /// </summary> public void Dispose() { if (_waitWrite != null) { _waitWrite.Dispose(); } }
/// <summary> /// Dispose /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { m_IsDisposed = true; if (m_ProcessEventWaitHandle != null) { m_ProcessEventWaitHandle.Set(); m_ProcessEventWaitHandle.Dispose(); m_ProcessEventWaitHandle = null; } if (m_IpcCommunication != null) { m_IpcCommunication.MessageRecived -= OnIpcCommunicationMessageRecived; m_IpcCommunication.Dispose(); m_IpcCommunication = null; } if (m_WorkerProcess != null) { WaitForRemoteProcessShutdown(); if (!m_WorkerProcess.HasExited) { m_WorkerProcess.Kill(); } m_WorkerProcess.Disposed -= OnWorkerProcessDisposed; m_WorkerProcess.Exited -= OnWorkerProcessExited; m_WorkerProcess.Dispose(); m_WorkerProcess = null; } }
/// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param> protected virtual void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!_disposed) { // If disposing equals true, dispose all managed // and unmanaged ResourceMessages. if (disposing) { if (_channelClosedWaitHandle != null) { _channelClosedWaitHandle.Dispose(); _channelClosedWaitHandle = null; } if (_channel != null) { _channel.Dispose(); _channel = null; } if (_dataReaderTaskCompleted != null) { _dataReaderTaskCompleted.Dispose(); _dataReaderTaskCompleted = null; } } // Note disposing has been done. _disposed = true; } }
public SocketReadResult Wait() { _socketReadComplete.WaitOne(); _socketReadComplete.Dispose(); _socketReadComplete = null; return(_result); }
/// <summary> /// オブジェクトのリソースを破棄する。 /// </summary> /// <param name="isDisposing">Dispose()からの呼び出しの場合にはtrue, GC空の呼び出しの場合にはfalse</param> protected void Dispose(bool isDisposing) { if (isDisposed) { return; } if (IsRunning) { Stop(); } if (isDisposing && (task != null)) { task.Dispose(); } if (isDisposing && (eventWaitHandle != null)) { eventWaitHandle.Dispose(); } if (isDisposing && (image != null)) { image.Dispose(); } isDisposed = true; }
/// <summary> /// Disposes objected used by the class. /// </summary> /// <param name="disposing">A Boolean that indicates whether the method call comes from a Dispose method (its value is true) or from a finalizer (its value is false).</param> /// <remarks> /// The disposing parameter should be false when called from a finalizer, and true when called from the IDisposable.Dispose method. /// In other words, it is true when deterministically called and false when non-deterministically called. /// </remarks> protected virtual void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { // Dispose managed objects owned by the class here. _cts?.Cancel(); // Wait for thread to drain if (_completionEvent != null && !_completionEvent.WaitOne(_timeoutSeconds * 1000)) { // TODO: Flow ILogger to this layer. // AppInsights.TrackEvent("SendQueue.Dispose: _completionEvent timeout!!!", "Timeout Seconds".PairWith(timeoutSeconds)); } _completionEvent?.Dispose(); _semaphore?.Dispose(); _cts?.Dispose(); } _disposed = true; }
public void TearDown() { if (_disposeCompleted != null) { _disposeCompleted.Dispose(); } }
/// <summary> /// 停止服务。 /// </summary> /// <remarks> /// 如果服务已经为停止状态,该方法不做任何操作。 /// 如果在调用Stop方法停止服务时还有运行中的任务,服务主线程会等待WaitExitMinute指定的超时分钟数。 /// </remarks> public void Stop() { if (IsRunning == false) { return; } serviceRunning = false; if (TaskThreads != null && TaskThreads.Length > 0) { for (int i = 0; i < TaskThreads.Length; i++) { TaskThreads[i].Stop(); } } bool IsSafeExited = true; if (CurrentThreadCount > 0 && SafeExitWaitHandle != null) { // 停止时还有任务未执行完成,等待任务执行完成 // 但在等待指定超时时间后,会强制结束。 TimeSpan timeout = ExitWaitTimeout > 0 ? TimeSpan.FromSeconds(ExitWaitTimeout) : TimeSpan.FromMilliseconds(-1); IsSafeExited = SafeExitWaitHandle.WaitOne(timeout); SafeExitWaitHandle.Dispose(); SafeExitWaitHandle = null; } // 通知服务已停止。 OnServiceStoped(new ServiceStopEventArgs(IsSafeExited)); }
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 static void Run(ISingleInstanceApp app, string[] args = null) { var mutex = new Mutex(true, $"SingleInstance_Mutex_{app.Id}"); var eventHandle = new EventWaitHandle(false, EventResetMode.AutoReset, $"SingleInstance_StartEvent_{app.Id}"); try { if (mutex.WaitOne(TimeSpan.Zero, true)) { var scheduler = SynchronizationContext.Current == null ? TaskScheduler.Current : TaskScheduler.FromCurrentSynchronizationContext(); WaitOrTimerCallback callback = delegate { Task.Factory.StartNew(() => app.Activate(), CancellationToken.None, TaskCreationOptions.None, scheduler); }; var registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(eventHandle, callback, null, Timeout.Infinite, false); app.Run(args); mutex.ReleaseMutex(); registeredWaitHandle.Unregister(null); } else { eventHandle.Set(); } } finally { eventHandle.Close(); eventHandle.Dispose(); mutex.Close(); mutex.Dispose(); } }
protected virtual void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { _cancellation.Cancel(); _thread.Join(); _thread = null; _waiter.Dispose(); _waiter = null; _worker.Dispose(); _worker = null; _queue.Dispose(); _queue = null; _cancellation.Dispose(); _cancellation = null; _providers.Clear(); } _disposed = true; }
public void Dispose() { if (_waitHandle != null) { _waitHandle.Dispose(); } }
/// <summary> Уничтожить координатор и освободить его ресурсы. </summary> public void Dispose() { if (_disposed) { return; } if (_controlThread != null) { _controlThread.Join(); _controlThread = null; } if (_pauseResumeCoorninationHandle != null) { _pauseResumeCoorninationHandle.Dispose(); _pauseResumeCoorninationHandle = null; } if (_exitCoordinationHandle != null) { _exitCoordinationHandle.Dispose(); _exitCoordinationHandle = null; } _disposed = true; }
private static bool TryAcquireOnce(EventWaitHandle @event, int timeoutMillis, CancellationToken cancellationToken) { // cancellation case if (cancellationToken.CanBeCanceled) { // ensures that if we are already canceled upon entering this method // we will cancel, not wait cancellationToken.ThrowIfCancellationRequested(); // cancellable wait based on // http://www.thomaslevesque.com/2015/06/04/async-and-cancellation-support-for-wait-handles/ var index = WaitHandle.WaitAny(new[] { @event, cancellationToken.WaitHandle }, timeoutMillis); switch (index) { case WaitHandle.WaitTimeout: // timeout @event.Dispose(); return(false); case 0: // event return(true); default: // canceled cancellationToken.ThrowIfCancellationRequested(); throw new InvalidOperationException("Should never get here"); } } // normal case return(@event.WaitOne(timeoutMillis)); }
public void Close() { if (connectionClosed != null) { bool isClosed = connectionClosed.WaitOne(0); if (!isClosed) { connectionClosed.Set(); connectionClosed.Dispose(); } connectionClosed = null; EventWaitHandle[] handles = { serverRead, serverWrote, clientRead, clientWrote }; for (int i = 0; i < handles.Length; i++) { if (handles[i] != null) { handles[i].Dispose(); } } if (data != null) { data.Dispose(); data = null; } } }
protected override void Dispose(bool disposing) { // make sure we've unsubscribed from all session events and closed the channel // before we starting disposing base.Dispose(disposing); if (disposing) { if (_socket != null) { lock (_socketLock) { if (_socket != null) { _socket.Dispose(); _socket = null; } } } if (_channelOpen != null) { _channelOpen.Dispose(); _channelOpen = null; } if (_channelData != null) { _channelData.Dispose(); _channelData = null; } } }
public void Dispose() { if (_attachDone != null) { _attachDone.Dispose(); } }
public void Dispose() { Cancel(); tokenSource?.Dispose(); pauseWait?.Dispose(); items?.Dispose(); }
public void RemoveQueue(long key, EventWaitHandle wh) { lock (_listona.SyncRoot) listona.Remove(key); wh.Dispose(); }
public void Dispose() { activeSolutionTracker.ActiveSolutionChanged -= ActiveSolutionTracker_ActiveSolutionChanged; analysisConfigMonitor.ConfigChanged -= AnalysisConfigMonitor_ConfigChanged; serverInitLocker?.Dispose(); }
/// <summary> /// Kills the thread and releases all resources used by the /// <see cref="ControlledRealTimeReopenThread{T}"/>. Also joins to the /// thread so that when this method returns the thread is no longer alive. /// </summary> // LUCENENET specific - Support for Dispose(bool) since this is a non-sealed class. protected virtual void Dispose(bool disposing) { // LUCENENET: Prevent double-dispose of our managed resources. if (isDisposed.GetAndSet(true)) { return; } if (disposing) { finish = true; // So thread wakes up and notices it should finish: reopenCond.Set(); try { Join(); } catch (Exception ie) when(ie.IsInterruptedException()) { throw new Util.ThreadInterruptedException(ie); } finally { RefreshDone(); // LUCENENET specific: dispose reset events reopenCond.Dispose(); m_notify.Dispose(); } } }