private void OnExecuteJob(object state) { Task allTask = null; try { Parallel.ForEach(_syncJobTypes, jobType => { IBackgroundJob job = null; try { using (var scope = _container.CreateScope()) { try { job = (IBackgroundJob)scope.Resolve(jobType); ScopeCreated(this, new ScopeCreatedEventArgs(scope)); job.Execute(); Signal.Reset("ApplicationServices[" + job.GetType() + "].Failed"); ScopeClosing(this, new ScopeClosingEventArgs(scope, true)); } catch (Exception exception) { Signal.Raise("ApplicationServices[" + jobType.FullName + "].Failed", "Failed to execute job.", exception); var args = new BackgroundJobFailedEventArgs(job ?? new NoJob(jobType, exception), exception); JobFailed(this, args); ScopeClosing(this, new ScopeClosingEventArgs(scope, false) { Exception = exception }); } } } catch (Exception exception) { JobFailed(this, new BackgroundJobFailedEventArgs(new NoJob(jobType, exception), exception)); _logger.Error("Failed to execute job: " + job, exception); } }); var tasks = _asyncJobTypes.Select(ExecuteAsyncJob); allTask = Task.WhenAll(tasks); allTask.Wait(); } catch (Exception exception) { _logger.Error("failed to execute jobs", exception); if (allTask != null) { JobFailed(this, new BackgroundJobFailedEventArgs(new NoJob(GetType(), allTask.Exception), exception)); } else { JobFailed(this, new BackgroundJobFailedEventArgs(new NoJob(GetType(), exception), exception)); } } }
private void ExecuteSyncJob(Type jobType) { IBackgroundJob job = null; try { using (var scope = _container.CreateScope()) { try { job = (IBackgroundJob)scope.Resolve(jobType); if (job == null) { throw new InvalidOperationException(string.Format("Failed to resolve job type '{0}'.", jobType.FullName)); } ScopeCreated(this, new ScopeCreatedEventArgs(scope)); job.Execute(); ScopeClosing(this, new ScopeClosingEventArgs(scope, true)); } catch (Exception exception) { var args = new BackgroundJobFailedEventArgs(job ?? new NoJob(jobType, exception), exception); JobFailed(this, args); ScopeClosing(this, new ScopeClosingEventArgs(scope, false) { Exception = exception }); } } } catch (Exception exception) { JobFailed(this, new BackgroundJobFailedEventArgs(new NoJob(jobType, exception), exception)); _logger.Error("Failed to execute job: " + job, exception); } }