/// <summary> /// Actual deconstructor in accordance with the dispose pattern /// </summary> /// <param name="disposing"> /// True if managed and unmanaged resources will be freed /// (otherwise only unmanaged resources are handled) /// </param> protected virtual void Dispose(bool disposing) { if (!disposed) { disposed = true; if (disposing) { Delegate[] delegateBuffer = null; monitorTimer.Elapsed -= new ElapsedEventHandler(TimerElapsed); monitorTimer.Dispose(); delegateBuffer = Elapsed.GetInvocationList(); foreach (ElapsedEventHandler item in delegateBuffer) { Elapsed -= item; } Elapsed = null; delegateBuffer = Reactivated.GetInvocationList(); foreach (EventHandler item in delegateBuffer) { Reactivated -= item; } Reactivated = null; } } }
private void ElapsedThreadProc() { while (true) { m_waitHandle.WaitOne(); if (m_disposing) { return; } ElapsedEventArgs eea = new ElapsedEventArgs(DateTime.Now); if (Elapsed != null) { foreach (ElapsedEventHandler eeh in Elapsed.GetInvocationList()) { // determine if we're supposed to Invoke or not if (SynchronizingObject == null) { eeh(this, eea); } else { SynchronizingObject.Invoke(eeh, new object[] { this, eea }); } } } } }
private async Task MainLoopAsync([NotNull] AsyncTimerStartedInstance currentInstance) { if (currentInstance == null) { throw new ArgumentNullException(nameof(currentInstance)); } try { currentInstance.CancellationToken.ThrowIfCancellationRequested(); await Task.Delay(initialDelay, currentInstance.CancellationToken); do { currentInstance.CancellationToken.ThrowIfCancellationRequested(); var actions = Elapsed ?.GetInvocationList() .ToArray() .Cast <AsyncTimerActionDelegate>(); if (actions == null) { continue; } var cancellationTokenCopy = currentInstance.CancellationToken; await Task.WhenAll(actions.Select(async action => { try { await action(cancellationTokenCopy); } catch (Exception exception) { try { var task = ExceptionOccurred?.Invoke(action, exception); if (task != null) { await task; } } catch { /* ignored */ } } })); currentInstance.CancellationToken.ThrowIfCancellationRequested(); await Task.Delay(interval, currentInstance.CancellationToken); }while (autoReset); } catch (TaskCanceledException) { /* expected */ } finally { // ReSharper disable once MethodSupportsCancellation await runningInstanceSemaphore.WaitAsync(); try { if (runningInstance == currentInstance) { runningInstance = null; } } finally { runningInstanceSemaphore.Release(); } try { currentInstance.Dispose(); } catch { /* ignored */ } } }