private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // First, handle the case where an exception was thrown. if (e.Error != null) { // MessageBox.Show(e.Error.Message); } else if (e.Cancelled) { // Next, handle the case where the user canceled // the operation. // Note that due to a race condition in // the DoWork event handler, the Cancelled // flag may not have been set, even though // CancelAsync was called. // resultLabel.Text = "Canceled"; } else { // Finally, handle the case where the operation // succeeded. // resultLabel.Text = e.Result.ToString(); } JobCompleted?.Invoke(sender, e); // Enable the UpDown control. }
/// <summary>Called by a runner process to signal end of job</summary> /// <param name="sender">The sender</param> /// <param name="args">The command arguments</param> private void OnEndJob(object sender, SocketServer.CommandArgs args) { try { EndJobArguments arguments = args.obj as EndJobArguments; JobCompleteArgs jobCompleteArguments = new JobCompleteArgs(); jobCompleteArguments.job = runningJobs[arguments.key]; if (arguments.errorMessage != null) { jobCompleteArguments.exceptionThrowByJob = new Exception(arguments.errorMessage); } lock (this) { if (JobCompleted != null) { JobCompleted.Invoke(this, jobCompleteArguments); } runningJobs.Remove(arguments.key); } server.Send(args.socket, "OK"); } catch (Exception err) { errors += err.ToString() + Environment.NewLine; } }
private async Task FinishOutput(BuildState buildState, JobCompletedEventArgs jobCompletedEventArgs) { if (buildOutputStream != null) { await buildOutputStream.FlushAsync(); buildOutputStream.Flush(flushToDisk: true); await buildOutputStream.DisposeAsync(); } int extraChars = outputDecoder.GetCharCount(Array.Empty <byte>(), 0, 0, flush: true); if (extraChars > 0) { var decoded = new char[extraChars]; outputDecoder.GetChars(Array.Empty <byte>(), 0, 0, decoded, 0, flush: true); AppendLineChars(decoded); } await FileUtil.WriteAllTextToDiskAsync( Path.Combine(buildDir, "result.json"), JsonConvert.SerializeObject(new JobBuildResult { State = buildState, }), Encoding.UTF8, CancellationToken.None ); outputLines.Add(currentLine.ToString()); OutputLinesChanged?.Invoke(this, new OutputLinesChangedEventArgs(outputLines)); state = buildState; complete.TrySetResult(null); JobCompleted?.Invoke(this, jobCompletedEventArgs); }
protected async void FireJobCompleted(JobEventArgs jobEventArgs) { var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher; await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { JobCompleted?.Invoke(this, jobEventArgs); }); }
public virtual void DoWork() { TimeToComplete -= Time.deltaTime; if (TimeToComplete <= 0) { OnJobCompleted?.Invoke(); } }
/// <summary> /// Invoke the job completed event. /// </summary> /// <param name="job"></param> /// <param name="jobManager"></param> /// <param name="startTime"></param> /// <param name="error"></param> protected void InvokeJobCompleted(IRunnable job, IJobManager jobManager, DateTime startTime, Exception error) { var finishTime = DateTime.Now; var arguments = new JobCompleteArguments() { Job = job, ExceptionThrowByJob = error, ElapsedTime = finishTime - startTime }; jobManager.JobHasCompleted(arguments); JobCompleted?.Invoke(this, arguments); }
public void OnJobCompleted(JobInfo job, bool notifyUser = false) { using var scope = scopeFactory.CreateScope(); using var dataContext = scope.ServiceProvider.GetRequiredService <DataContext>(); job.State = JobState.Completed; job.Completed = DateTimeOffset.UtcNow; dataContext.SaveChanges(); userLogger.LogInfo("Job completed", userId: job.UserId, jobId: job.Id); JobCompleted?.Invoke(this, new JobCompletedEventArgs() { Job = job }); }
public bool Execute() { var startTime = DateTime.Now; try { m_CurrentCancellationToken = new CancellationTokenSource(); var cancellationToken = m_CurrentCancellationToken.Token; using (var prg = m_App.CreateProgress()) { LogMessage("Preparing job"); var jobItems = PrepareJob(); JobSet?.Invoke(jobItems, startTime); for (int i = 0; i < jobItems.Length; i++) { cancellationToken.ThrowIfCancellationRequested(); var jobItem = jobItems[i]; prg.SetStatus($"Processing {jobItem.FilePath}"); var res = TryProcessFile(jobItem, cancellationToken); ProgressChanged?.Invoke(jobItem, res); prg.Report((double)(i + 1) / (double)jobItems.Length); } } return(true); } catch (OperationCanceledException) { throw new JobCancelledException(); } catch (Exception ex) { m_Logger.Log(ex); return(false); } finally { JobCompleted?.Invoke(DateTime.Now - startTime); } }
/// <summary>Run the specified jobs</summary> /// <param name="jobs">An instance of a class that manages all jobs.</param> /// <param name="wait">Wait until all jobs finished before returning?</param> /// <param name="numberOfProcessors">The maximum number of cores to use.</param> public void Run(IJobManager jobs, bool wait = false, int numberOfProcessors = -1) { // No - get another job to run. IRunnable job = jobs.GetNextJobToRun(); CancellationTokenSource cancelToken = new CancellationTokenSource(); // Iterate through all jobs and run them. while (job != null) { JobCompleteArgs jobCompleteArguments = new JobCompleteArgs(); jobCompleteArguments.job = job; try { job.Run(cancelToken); } catch (Exception err) { jobCompleteArguments.exceptionThrowByJob = err; } if (JobCompleted != null) { JobCompleted.Invoke(this, jobCompleteArguments); } job = jobs.GetNextJobToRun(); } Exception exceptionThrown = null; try { jobs.Completed(); } catch (Exception err) { exceptionThrown = err; } if (AllJobsCompleted != null) { AllJobsCompleted.Invoke(this, new AllCompletedArgs() { exceptionThrown = exceptionThrown }); } }
/// <summary>Main DoWork method for the scheduler thread. NB this does NOT run on the UI thread. /// </summary> /// <param name="jobs">An instance of a class that manages all jobs.</param> private void JobRunnerThread(IJobManager jobs) { // No - get another job to run. IRunnable job = jobs.GetNextJobToRun(); Exception exceptionThrown = null; try { // Iterate through all jobs and run them. while (job != null && !cancelToken.IsCancellationRequested) { JobCompleteArgs jobCompleteArguments = new JobCompleteArgs(); jobCompleteArguments.job = job; try { job.Run(cancelToken); } catch (Exception err) { jobCompleteArguments.exceptionThrowByJob = err; } if (JobCompleted != null) { JobCompleted.Invoke(this, jobCompleteArguments); } job = jobs.GetNextJobToRun(); } jobs.Completed(); } catch (Exception err) { exceptionThrown = err; } allJobsFinished = true; AllJobsCompleted?.Invoke(this, new AllCompletedArgs() { exceptionThrown = exceptionThrown }); }
public Task <bool> ExecuteAsync() { var startTime = DateTime.Now; try { using (var prg = m_App.CreateProgress()) { LogMessage("Preparing job"); var jobItems = PrepareJob(); JobSet?.Invoke(jobItems, startTime); for (int i = 0; i < jobItems.Length; i++) { var jobItem = jobItems[i]; prg.SetStatus($"Processing {jobItem.FilePath}"); var res = TryProcessFile(jobItem, default); ProgressChanged?.Invoke(jobItem, res); prg.Report((double)i / (double)jobItems.Length); } } return(Task.FromResult(true)); } catch { return(Task.FromResult(false)); } finally { JobCompleted?.Invoke(DateTime.Now - startTime); } }
/// <summary>Main DoWork method for the scheduler thread. NB this does NOT run on the UI thread. /// </summary> /// <param name="jobs">An instance of a class that manages all jobs.</param> /// <param name="numberOfTasksToUse">The number of tasks to run asyhchronously</param> private void JobRunnerThread(IJobManager jobs, int numberOfTasksToUse = -1) { Exception exceptionThrown = null; try { numberTasksRunning = 0; // Main worker thread for keeping jobs running while (!cancelToken.IsCancellationRequested) { // Have we reached our maximum number of running jobs? if (numberTasksRunning >= numberOfTasksToUse) { Thread.Sleep(200); // Yes } else { // No - get another job to run. IRunnable job = jobs.GetNextJobToRun(); // If no job available then exit - we're done. if (job == null) { break; } // If the job is computationally intensive and will potentially take some time // to run, then we want to keep track of how many of these are running. if (typeof(IComputationalyTimeConsuming).IsAssignableFrom(job.GetType())) { lock (this) numberTasksRunning++; } // Run the job. Task.Run(() => { JobCompleteArgs jobCompleteArguments = new JobCompleteArgs(); jobCompleteArguments.job = job; try { job.Run(cancelToken); } catch (Exception err) { jobCompleteArguments.exceptionThrowByJob = err; } if (JobCompleted != null) { JobCompleted.Invoke(this, jobCompleteArguments); } lock (this) numberTasksRunning--; }); } } // All jobs now completed while (numberTasksRunning > 0) { Thread.Sleep(200); } jobs.Completed(); } catch (Exception err) { exceptionThrown = err; } if (AllJobsCompleted != null) { AllJobsCompleted.Invoke(this, new AllCompletedArgs() { exceptionThrown = exceptionThrown }); } }
private void OnJobCompleted(TimeSpan duration) => JobCompleted?.Invoke(duration);
protected virtual void OnJobCompleted(Worker worker, Job job) { JobCompleted?.Invoke(worker, job); }
protected virtual void OnJobCompleted(object sender, EventArgs e) { JobCompleted?.Invoke(sender, e); }
public void NotifyJobCompleted() { JobCompleted?.Invoke(this, EventArgs.Empty); }
public static void OnJobCompleted(object sender, JobStatus e) { JobCompleted?.Invoke(sender, e); }
public void OnJobCompleted(IJob e) { JobCompleted?.Invoke(this, e); }
public void InvokeJobCompleted(TranslationJob job) { JobCompleted?.Invoke(job); }
protected virtual void OnJobCompleted(JobCompletedEventArgs e) => JobCompleted?.Invoke(this, e);
private void OnJobCompleted(JobCompletedEventArgs eventArgs) => JobCompleted?.Invoke(this, eventArgs);
/// <summary>Main DoWork method for the scheduler thread. NB this does NOT run on the UI thread. /// </summary> /// <param name="jobs">An instance of a class that manages all jobs.</param> /// <param name="numberOfTasksToUse">The number of tasks to run asyhchronously</param> private void JobRunnerThread(IJobManager jobs, int numberOfTasksToUse = -1) { Exception exceptionThrown = null; try { int numberTasksRunning = 0; // Main worker thread for keeping jobs running while (!cancelToken.IsCancellationRequested) { // Have we reached our maximum number of running jobs? if (numberTasksRunning >= numberOfTasksToUse) { Thread.Sleep(200); // Yes } else { // No - get another job to run. IRunnable job = jobs.GetNextJobToRun(); // If no job available then exit - we're done. if (job == null) { break; } lock (this) numberTasksRunning++; // Run the job. Task.Run(() => { JobCompleteArgs jobCompleteArguments = new JobCompleteArgs(); jobCompleteArguments.job = job; try { job.Run(cancelToken); } catch (Exception err) { jobCompleteArguments.exceptionThrowByJob = err; } if (JobCompleted != null) { JobCompleted.Invoke(this, jobCompleteArguments); } lock (this) numberTasksRunning--; }); } } // All jobs now completed while (numberTasksRunning > 0) { Thread.Sleep(200); } jobs.Completed(); } catch (Exception err) { exceptionThrown = err; } if (AllJobsCompleted != null) { AllJobsCompleted.Invoke(this, new AllCompletedArgs() { exceptionThrown = exceptionThrown }); } }
public WorkflowResult Execute() { //A given instance of this class should only be executable one time since we hold //on to processing and error state at the end of the run. //We're not expecting this class to be used in a multi-threaded situation, but //just the same, it's easy to prevent that unintended usage, so we'll do so here. lock (_syncObject) { if (Complete || Executed) { throw new InvalidOperationException("The process may only be executed once."); } Executed = true; } JobStarted?.Invoke(); var rollback = false; for (var i = 0; i < _steps.Count; ++i) { CurrentStep = i; var step = _steps[i]; try { RunStep(step); _lastStepCompleted = i; } catch (Exception e) { ActionException = e; Error = true; ErrorMessage = step.GetFormattedFailureMessage(e); _logger.Error($"{WorkflowName} - {ErrorMessage}"); rollback = true; break; } } if (rollback) { Rollback(); } Complete = true; JobCompleted?.Invoke(); return(new WorkflowResult { Error = Error, ActionException = ActionException, ErrorDuringRollback = ErrorDuringRollback, ErrorMessage = ErrorMessage, RollbackErrorMessage = RollbackErrorMessage, RollbackException = RollbackException, TotalSteps = TotalSteps, StepsCompletedSuccessfully = StepsCompletedSuccessfully, StepsRolledBack = StepsRolledBack }); }