public JobManager() { _log = new List <string> { string.Format("[{0:yyyy-MM-dd HH:mm:ss}] Queue started.", DateTime.Now) }; _queue = new BlockingCollection <ServiceJob>(); Task.Run(async() => { while (true) { ServiceJob job = null; try { job = _queue.Take(); if (job != null) { await Pop(job); } } catch (Exception ex) { OnJobError(job, ex); } } }); }
private async Task <bool> Pop(ServiceJob job) { var sw = System.Diagnostics.Stopwatch.StartNew(); _log.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] Started job ID {job.ID} ({job.Name})."); if (job.Action != null) { bool result = await job.Action(); sw.Stop(); _log.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] Completed job ID {job.ID} ({job.Name}) in {sw.Elapsed.TotalSeconds:0.00} seconds. Result: {result}"); return(result); } else { _log.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] Unable to process job. {job.Name} does not have an action to execute."); throw new InvalidOperationException($"Unable to process job. {job.Name} does not have an action to execute."); } }
protected virtual void OnJobError(ServiceJob job, Exception ex) { JobError?.Invoke(this, new JobException(job, ex)); }
public void Push(ServiceJob job) { _queue.Add(job); }
internal JobException(ServiceJob job, Exception ex) { Job = job; Exception = ex; }