void wkfn() { try { WaitHandle[] handles = new WaitHandle[] { _evHasData, _evStop.WaitHandle }; while (true) { _operationStarted = 0; int idx = WaitHandle.WaitAny(handles); if (idx == 0) { T workUnit; while (_queue.TryDequeue(out workUnit)) { Interlocked.Exchange(ref _operationStarted, DateTime.UtcNow.ToBinary()); try { if (null != workUnit) { try { ExecuteTask(workUnit); } catch (Exception ex) { _logger.Exception(string.Format("AT processing {0}", GetTaskDescription(workUnit)), ex); } } else { _logger.Error("Thread {0}: null work in queue.", Name); } } finally { _operationStarted = 0; } } } else { break; } } } catch (ThreadAbortException) { Thread.ResetAbort(); } catch (Exception ex) { _logger.Exception(string.Format("Main wkfn of '{0}' was broken", Name), ex); } }
void processMail(CancellationToken token) { if (_mailsActiveCount > _maxParallelMessages) { return; } Interlocked.Increment(ref _mailsActiveCount); QueuedMail msg = null; try { if (!token.IsCancellationRequested && _mainQueue.TryDequeue(out msg)) { DateTime dt = DateTime.UtcNow; using (ISmpClient cli = _clifac.Create()) { cli.Send(msg.Msg); } if ((DateTime.UtcNow - dt).TotalSeconds > WarnTimeInSec) { _logger.Warn("Sending mail '{0}', to {1} took extratime: {2}s", msg.Msg.Subject, msg.Msg.Recipients, (DateTime.UtcNow - dt).TotalSeconds); } msg.Msg.Dispose(); } } catch (Exception ex) { _logger.Exception(string.Format("On sending news, queue size = {0}", _mainQueue.Count), ex); if (!token.IsCancellationRequested) { msg.LastError = ex; _retryQueue.Enqueue(msg); startRetrying(); } } finally { Interlocked.Decrement(ref _mailsActiveCount); } if (_mainQueue.Count > 0 && !token.IsCancellationRequested) { startSending(); } }
public int Run(string[] commandLineArgs = null) { try { _logger.Info("Processing command line switches"); processCommandLine(commandLineArgs); _logger.Info("Command line switches were processed"); } catch (Exception exc) { Environment.ExitCode = -1; Console.WriteLine("During processing command line exception happened: {0}", exc.ToString()); return(Environment.ExitCode); } if (!_donotStartService) { bool running = false; try { _logger.Info("Service host is being constructed"); using (IRuntimeHost host = constructServiceHost()) { _logger.Info("Service host was constructed"); running = true; _logger.Info("Service host is being started"); host.Run(_testMode, commandLineArgs); _logger.Info("Service host was finished"); } } catch (Exception ex) { Environment.ExitCode = -2; _logger.Exception(running ? "Starting host":"Constructing host", ex); if (_testMode) { Console.WriteLine("{0}: {1}", running ? "Starting host":"Constructing host", ex); } } } return(Environment.ExitCode); }
protected override void Dispose(bool disposing) { if (disposing) { if (!_stateMachine.IsInFinalState) { try { _stateMachine.Transit(_stateMachine.FinalState, CancellationToken.None).Wait(startStopTimeoutMS); } catch (Exception ex) { _logger.Exception(string.Format("At closing host '{0}'", WinServiceName), ex); } } } base.Dispose(disposing); }
public void Dispose() { if (!_stateMachine.IsInFinalState) { try { _stateMachine.Transit(_stateMachine.FinalState, CancellationToken.None).Wait(DisposingTimeoutSeconds); } catch (Exception ex) { _logger.Exception(string.Format("At closing service '{0}'", _stateMachine.Name), ex); } } }
/// <summary> /// Выполняет задачу. /// </summary> void executer(object task) { #if DEBUG int ec = Interlocked.Increment(ref _entranceCount); if (ec > 1) { _logger.Error("ThreadPoolSequentialExecuter: task parallel execution is detected '{0}'", ec); } #endif if (Thread.VolatileRead(ref _disposed) == 0) { T tt = (T)task; Exception excKeep = null; try { ExecuteTask(tt); } catch (Exception ex) { excKeep = ex; _logger.Exception("Error of a task execution", ex); } try { onTaskFinished(tt, excKeep); } catch (Exception ex) { _logger.Exception("Error of a task execution/finishing", ex); } } #if DEBUG Interlocked.Decrement(ref _entranceCount); #endif trySpawnNextTask(); }
void wkfn(object st) { try { foreach (IMonitorable <T> drb in _controlables) { drb.PerformMonitoring(_monitorActivity); } } catch (Exception ex) { _logger.Exception("ThreadMonitor: CheckHungingUp", ex); } Timer t = _t; if (t != null) { try { t.Change(_monitorPeriodMS, Timeout.Infinite); } catch {} } }
public async Task <TState> Transit(TState newState, CancellationToken cts, object args = null) { if (_logTransitions) { _logger.Info("Machine '{0}' is about to transit {1} --> {2}", Name, State, newState); } if (!StateDef <TState> .IsValid(newState)) { return(await compliteWithError(new Exception(string.Format("State '{0}' is invalid for machine '{1}'", newState, Name)))); } if (IsInFinalState) { return(await compliteWithError(new Exception(string.Format("Machine '{0}' can't transit to state '{1}' because it is in final state '{2}'", Name, newState, _state.Final)))); } int res = Interlocked.Exchange(ref _isInTransition, 1); //блокировка транзишенов до тех пор, пока не заевршится текущий транзишен if (res != 0) { if (EqualityComparer <TState> .Default.Equals(newState, FinalState)) //разрешаем только рекурсивный Close { _logger.Warn("Machine '{0}' started reqursive transition {1} --> {2}", Name, State, newState); } else { return(await compliteWithError(new Exception(string.Format("In machine '{0}' reqursive transition {1} --> {2} has been detected", Name, State, newState)))); } } TState transitionResult = State; CancellationTokenRegistration reg = default(CancellationTokenRegistration); bool lockCleared = false; try { TState stateFrom = State; TransitionDef <TState> transition = getTransition(stateFrom, newState); if (transition == TransitionDef <TState> .Empty) { throw new Exception(string.Format("Machine '{0}' didn't find transition {1} --> {2}", Name, stateFrom, newState)); } if (_logTransitions) { _logger.Info("Machine '{0}' is transiting {1} --> {2}", Name, stateFrom, newState); } if (transition.StateActivityAsync != null) { try { TransitionState = _state.GetTransitionalState(State, newState); if (TransitionState != null) { onStateChanging(TransitionState.Value); } reg = cts.Register(() => { lockCleared = true; Interlocked.Exchange(ref _isInTransition, 0); }); transitionResult = await transition.StateActivityAsync(stateFrom, newState, cts, args).WithAllExceptions().ConfigureAwait(false); cts.ThrowIfCancellationRequested(); State = transitionResult; if (_logTransitions) { _logger.Info("Machine '{0}' transited {1} --> {2}", Name, stateFrom, newState); } onStateChanged(stateFrom, transitionResult); } catch (AggregateException ex) { _logger.Error("Machine '{0}' failed to transit {1} --> {2}", Name, stateFrom, newState); onStateChanged(stateFrom, transitionResult, ex); ex.Handle((err) => { if (err is OperationCanceledException) { _logger.Warn("Machine '{0}' transition {1} --> {2} was cancelled", Name, stateFrom, newState); return(true); } return(false); }); } catch (OperationCanceledException ce) { _logger.Warn("Machine '{0}' transition {1} --> {2} was cancelled", Name, stateFrom, newState); onStateChanged(stateFrom, transitionResult, ce); } catch (Exception ex) { _logger.Exception(string.Format("Machine '{0}' failed to transit {1} --> {2}", Name, stateFrom, newState), ex); onStateChanged(stateFrom, transitionResult, ex); throw; } } else { State = newState; transitionResult = newState; if (_logTransitions) { _logger.Info("Machine '{0}' transited {1} --> {2} with no action", Name, stateFrom, newState); } onStateChanged(stateFrom, newState); } } finally { if (!lockCleared) { Interlocked.Exchange(ref _isInTransition, 0); TransitionState = null; } } return(transitionResult); }