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.
 }
Exemplo n.º 2
0
 /// <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;
     }
 }
Exemplo n.º 3
0
        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);
        }
Exemplo n.º 4
0
 protected async void FireJobCompleted(JobEventArgs jobEventArgs)
 {
     var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
     await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         JobCompleted?.Invoke(this, jobEventArgs);
     });
 }
Exemplo n.º 5
0
    public virtual void DoWork()
    {
        TimeToComplete -= Time.deltaTime;

        if (TimeToComplete <= 0)
        {
            OnJobCompleted?.Invoke();
        }
    }
Exemplo n.º 6
0
        /// <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);
        }
Exemplo n.º 7
0
        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
            });
        }
Exemplo n.º 8
0
        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);
            }
        }
Exemplo n.º 9
0
        /// <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
                });
            }
        }
Exemplo n.º 10
0
        /// <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
            });
        }
Exemplo n.º 11
0
        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);
            }
        }
Exemplo n.º 12
0
        /// <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
                });
            }
        }
Exemplo n.º 13
0
 private void OnJobCompleted(TimeSpan duration) => JobCompleted?.Invoke(duration);
Exemplo n.º 14
0
 protected virtual void OnJobCompleted(Worker worker, Job job)
 {
     JobCompleted?.Invoke(worker, job);
 }
Exemplo n.º 15
0
 protected virtual void OnJobCompleted(object sender, EventArgs e)
 {
     JobCompleted?.Invoke(sender, e);
 }
Exemplo n.º 16
0
 public void NotifyJobCompleted()
 {
     JobCompleted?.Invoke(this, EventArgs.Empty);
 }
 public static void OnJobCompleted(object sender, JobStatus e)
 {
     JobCompleted?.Invoke(sender, e);
 }
Exemplo n.º 18
0
 public void OnJobCompleted(IJob e)
 {
     JobCompleted?.Invoke(this, e);
 }
 public void InvokeJobCompleted(TranslationJob job)
 {
     JobCompleted?.Invoke(job);
 }
Exemplo n.º 20
0
 protected virtual void OnJobCompleted(JobCompletedEventArgs e) => JobCompleted?.Invoke(this, e);
Exemplo n.º 21
0
 private void OnJobCompleted(JobCompletedEventArgs eventArgs) => JobCompleted?.Invoke(this, eventArgs);
Exemplo n.º 22
0
        /// <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
                });
            }
        }
Exemplo n.º 23
0
        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
            });
        }