protected ExecutingContext(ExecutingContext executingContext) { CancellationTokenSource = executingContext.CancellationTokenSource; CancellationToken = executingContext.CancellationToken; EventId = executingContext.EventId; Sw = executingContext.Sw; }
private async Task DoWork(CancellationToken cancellationToken) { try { if (IsStillProcessing) { throw new Exception("still processing"); } IsStillProcessing = true; while (!cancellationToken.IsCancellationRequested) { PeriodicServiceRepository.Update(Options, Interation); if (!Options.Enabled) { Logger.LogInformation($"Service {Options.ServiceName} disabled"); return; } var ec = new ExecutingContext(cancellationToken) { EventId = new EventId(0, $"{Options.ServiceName}_{++Interation}") }; if (Logging.LogLevel.Gg <= LogLevel.Debug) { Logger.LogDebug(ec.EventId, $"processing {Options.ServiceName} iteration {Interation} at {ec.Sw.ElapsedMilliseconds}ms"); } try { await DoWork(ec); PeriodicServiceRepository.UpdateRun(Options, Interation, ec.Sw.ElapsedMilliseconds, null); } catch (Exception e) { Logger.LogError(ec.EventId, e, $"Error processing {Options.ServiceName} at {ec.Sw.ElapsedMilliseconds}ms"); PeriodicServiceRepository.UpdateRun(Options, Interation, ec.Sw.ElapsedMilliseconds, e.ToString()); } if (Logging.LogLevel.Gg <= LogLevel.Debug) { Logger.LogDebug(ec.EventId, $"finish processing {Options.ServiceName} iteration {++Interation} at {ec.Sw.ElapsedMilliseconds}ms"); } Task.Delay(Options.PeriodMilliseconds, cancellationToken).Wait(cancellationToken); } } catch (Exception e) { Logger.LogError(e, $"Error {Options.ServiceName} iteration {Interation}. Stop worker"); } IsStillProcessing = false; }
protected abstract Task DoWork(ExecutingContext ec);