Пример #1
0
        private async Task RunRecurrentTaskAsync(Lazy <IRecurrentTask, RecurrentTaskMetadata> recurrentTask)
        {
            object result   = null;
            var    executed = false;

            try
            {
                if (await recurrentTask.Value.CanExecuteAsync(_cancellationTokenSource.Token).ConfigureAwait(false))
                {
                    _logger.LogEvent(RunTaskEvent, $"Task: {recurrentTask.Metadata.Name}");
                    executed = true;
                    result   = await recurrentTask.Value.ExecuteAsync(_cancellationTokenSource.Token).ConfigureAwait(false);
                }
            }
            catch (OperationCanceledException) { }
            catch (Exception ex)
            {
                _logger.LogFault(RunTaskFaultEvent, $"Failed to run recurrent task '{recurrentTask.Metadata.Name}'.", ex);
            }
            finally
            {
                if (executed)
                {
                    await TaskHelper.RunOnUIThreadAsync(() =>
                    {
                        TaskCompleted?.Invoke(this, new RecurrentTaskEventArgs(recurrentTask.Metadata.Name, result));
                    }).ConfigureAwait(false);
                }
            }
        }
Пример #2
0
 public void Handle(TaskCompleted <SaveContactResult> taskCompleted)
 {
     if (taskCompleted.Result.TaskResult == TaskResult.OK)
     {
         ImportContactsAsync();
     }
 }
Пример #3
0
        public void Test()
        {
            TaskCompleted callback     = TestCallBack;
            CallBack      testCallBack = new CallBack();

            testCallBack.StartNewTask(callback);
        }
Пример #4
0
 public void Task(TaskCompleted taskCompleted)
 {
     Console.WriteLine("starting task");
     if (taskCompleted != null)
     {
         taskCompleted("task completed");
     }
 }
Пример #5
0
 public void StartNewTask(TaskCompleted taskCompleted)
 {
     Console.WriteLine("Initializing the task...");
     if (taskCompleted != null)
     {
         taskCompleted("Task Finished!!!");
     }
 }
 private void OnTaskCompleted(ScheduledTask <T> task, ISchedulerAction action)
 {
     try
     {
         TaskCompleted?.Invoke(this, new ScheduledTaskCompletedEventArgs <T>(task, action.IsSuccess, action.IsCanceled, action.Exception, action.State));
     }
     catch { }
 }
Пример #7
0
        public ClientResult Post([FromBody] TaskCompleted signal)
        {
            return(new ClientResult
            {
                State = true,

                Message = $"Signal TaskCompleted"
            });
        }
Пример #8
0
 protected virtual void OnTaskCompleted <T>(T input)
 {
     count--;
     TaskCompleted?.Invoke(this, new EventArgs <object>(input));
     if (count == 0)
     {
         OnCompleted();
     }
 }
Пример #9
0
        public void Handle(TaskCompleted @event)
        {
            if (@event.QueueId != queueId)
            {
                return;
            }

            timer.Stop();
        }
Пример #10
0
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 public Task(TaskCompleted taskCompletedCallBack, object userData, ParameterizedThreadStart task, bool bContinuousExecution)
 {
     m_returnData = default(T);
     TaskOp      += task;
     Event        = null;
     SetCompleteEvent(taskCompletedCallBack);
     UserData            = userData;
     ContinuousExecution = bContinuousExecution;
 }
Пример #11
0
        /// <summary>
        /// Add a <see cref="TaskCompleted"/> callback
        /// </summary>
        /// <param name="callback"><see cref="TaskCompleted"/> callback to add</param>
        /// <returns>The <see cref="TaskContext"/></returns>
        public TaskContext Completed(TaskCompleted callback)
        {
            if (IsComplete)
            {
                callback(this);
            }

            _completed += callback;
            return(this);
        }
Пример #12
0
        //----------------------------------------------------------------------------------
        //----------------------------------------------------------------------------------
        public void Load(String szAssetGroupName, TaskCompleted callBack)
        {
            TaskHandle taskHandle;

            if (!IsChunkAlreadyLoaded(szAssetGroupName, callBack))
            {
                taskHandle = TaskManager.Instance.CreateTask <Object>(new TaskCompleted[] { AssetLoadedCallBack, callBack }, szAssetGroupName, m_iLoader.Load, false);
                TaskManager.Instance.ExecuteTask(taskHandle);
            }
        }
Пример #13
0
 public void OnMultipleDownloadsCompleted(object sender, EventArgs e)
 {
     ComicConvert.ImgsToCbz(repo.Location, OutputFileName);
     Active = false;
     Status = "Finished";
     if (TaskCompleted != null)
     {
         TaskCompleted.Invoke(this, new EventArgs());
     }
 }
 private void OnTaskCompleted(SharpEncryptTaskModel task)
 {
     TaskCompleted?.Invoke(task);
     if (!DisableAfterTaskCompleted)
     {
         return;
     }
     Disabled = true;
     BackgroundWorkerDisabled?.Invoke(Identifier);
 }
Пример #15
0
        /// <summary>
        /// Called when [task completed].
        /// </summary>
        /// <param name="task">The task.</param>
        /// <param name="result">The result.</param>
        internal void OnTaskCompleted(IScheduledTaskWorker task, TaskResult result)
        {
            TaskCompleted?.Invoke(task, new TaskCompletionEventArgs
            {
                Result = result,
                Task   = task
            });

            ExecuteQueuedTasks();
        }
Пример #16
0
        /// <summary>
        ///
        /// </summary>
        protected virtual void OnTaskCompleted <T>(T Result)
        {
            count--;

            TaskCompleted?.Invoke(this, new ResultEventArgs(Result));

            if (count == 0)
            {
                OnCompleted();
            }
        }
Пример #17
0
        private void OnRunningTaskCompleted(Task task)
        {
            RunningTask             runningTask             = null;
            CancellationTokenSource cancellationTokenSource = null;
            var cancellationToken = default(CancellationToken);

            var exception = task.Exception;

            var stringBuilder = new StringBuilder();

            stringBuilder.AppendLine($"Task completed, searching for existing running task");
            stringBuilder.AppendLine($"  * Canceled: {task.IsCanceled}");
            stringBuilder.AppendLine($"  * Completed: {task.IsCompleted}");
            stringBuilder.AppendLine($"  * Faulted: {task.IsFaulted}");
            stringBuilder.AppendLine($"  * Exception: {exception}");

            Log.Debug(stringBuilder.ToString());

            lock (_lock)
            {
                for (var i = 0; i < _runningTasks.Count; i++)
                {
                    var possibleRunningTask = _runningTasks[i];
                    if (ReferenceEquals(possibleRunningTask.Task, task))
                    {
                        runningTask = possibleRunningTask.RunningTask;

                        _runningTasks.RemoveAt(i);

                        cancellationTokenSource = possibleRunningTask.RunningTask.CancellationTokenSource;
                        cancellationToken       = cancellationTokenSource.Token;
                        cancellationTokenSource.Dispose();

                        break;
                    }
                }
            }

            if (runningTask is not null)
            {
                Log.Debug($"Found task '{runningTask}' for the completed task");

                if (runningTask.ScheduledTask.ScheduleRecurringTaskAfterTaskExecutionHasCompleted)
                {
                    RescheduleRecurringTask(runningTask);
                }

                if (!task.IsCanceled && !cancellationTokenSource.IsCancellationRequested &&
                    !_cancelledTokenSources.Contains(cancellationToken))
                {
                    TaskCompleted?.Invoke(this, new TaskEventArgs(runningTask));
                }
            }
        }
Пример #18
0
        public async Task RunTaskAsync(string title, Action <CancellationToken, IProgress <int> > task, Action <int> progressUpdate, Action taskCompleted)
        {
            if (_task != null)
            {
                throw new Exception("A task is already running.");
            }

            cancellationTokenSource = new CancellationTokenSource();
            cancellationToken       = cancellationTokenSource.Token;

            TaskStarted?.Invoke(this, null);

            _progressDialog = new ProgressDialog(this, _owner, $"Task - {title}", Maximum, Interval);
            _progressDialog.Show();

            var progress = new Progress <int>(percent =>
            {
                progressUpdate(percent);
            });

            try
            {
                _task = Task.Run(() =>
                {
                    task(cancellationToken, progress);
                }, cancellationToken);

                // wait for worker task to finish.
                await _task;
            }
            catch (TaskCanceledException)
            {
                Console.WriteLine("Task cancelled.");
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }

            SystemSounds.Beep.Play();

            taskCompleted();

            _progressDialog.Close();

            TaskCompleted?.Invoke(this, null);

            _progressDialog = null;
            _task           = null;
        }
Пример #19
0
        public async Task <bool> StartTask(string tempInputFolderPath, string tempOutputFolderPath, string waifu2xCaffePath, string ffmpegPath)
        {
            bool faulted = false;

            try
            {
                if (!Initialize())
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                TaskFaulted?.Invoke(this, $"Error occurred during initialization: {e.Message}");
                Logger.Error("An exception occurred during initialization: {@Exception}", e);
                faulted = true;
            }

            bool taskSucceeded = false;

            if (!faulted)
            {
                try
                {
                    taskSucceeded = await Start(tempInputFolderPath, tempOutputFolderPath, waifu2xCaffePath, ffmpegPath);
                }
                catch (Exception e)
                {
                    taskSucceeded = false;
                    TaskFaulted?.Invoke(this, $"Error occurred while processing: {e.Message}");
                    Logger.Error("An exception occurred while processing: {@Exception}", e);
                }
            }

            TaskCompleted?.Invoke(this);

            try
            {
                return(Dispose());
            }
            catch (Exception e)
            {
                if (!faulted)
                {
                    TaskFaulted?.Invoke(this, $"Error occurred while running cleanup: {e.Message}");
                }

                return(false);
            }
        }
        public void Invoke(CommandLineApplication app)
        {
            CommandOption fullScreenOpt = app.Option("-fullscreen", null, CommandOptionType.SingleValue);
            CommandOption languageOpt   = app.Option("-language", null, CommandOptionType.MultipleValue);
            CommandOption roleOpt       = app.Option("-role", null, CommandOptionType.SingleValue);
            CommandOption awaitedOpt    = app.Option("-awaited", null, CommandOptionType.SingleValue);
            CommandOption closeOpt      = app.Option("-close", null, CommandOptionType.SingleOrNoValue);

            app.OnExecute(() =>
            {
                int awaited        = 0;
                bool fullScreen    = false;
                bool closeWhenDone = false;
                string role        = roleOpt.Value();
                string[] language  = languageOpt.Values.ToArray();
                int.TryParse(awaitedOpt.Value(), out awaited);

                bool.TryParse(closeOpt.Value(), out closeWhenDone);
                bool.TryParse(fullScreenOpt.Value(), out fullScreen);

                InitializeWebBrowser();

                if (fullScreen)
                {
                    driver.Manage().Window.Maximize();
                }
                driver.Navigate().GoToUrl(TargetUri);

                driver.WaitElement(ClearFiltersXpath);
                driver.Scroll(ClearFiltersXpath);
                driver.ClickXp(LangXpath);

                LangFilter.Invoke(driver, language);
                driver.ClickXp(LangXpath);
                driver.ClickXp(DepartsXpath);

                DepartmentFilter.Invoke(driver, role);
                Count = driver.GetElementsCount(AwaliableVacansions);

                if (TaskCompleted != null)
                {
                    TaskCompleted.Invoke(awaitedVacansionsCount: awaited, realVacansionsCount: Count);
                }

                if (closeWhenDone)
                {
                    driver.Dispose();
                }
            });
        }
Пример #21
0
        public void ExecuteTask(Assembly task, Object[] parameters, GruntTaskingMessage message)
        {
            string output = "";

            try
            {
                var results = task.GetType("Task").GetMethod("Execute").Invoke(null, parameters);
                if (results != null)
                {
                    output = (string)results;
                }
                TaskCompleted?.Invoke(this, new TaskCompletedArgs(message, output));
            }
            catch (Exception e)
            { TaskCompleted?.Invoke(this, new TaskCompletedArgs(message, "TaskHandler Exception: " + e.Message + "\n" + e.StackTrace)); }
        }
Пример #22
0
        private void RaiseTaskCompleted(IBackgroundTask task, object state)
        {
            TaskCompleted?.Invoke(task, state);

            lock (_tasks)
            {
                if (_tasks.Count > 0)
                {
                    _uiDispatcher.Dispatch(() => _tasks.Dequeue());
                }
                else
                {
                    _taskIsRunning = false;
                }
            }
        }
Пример #23
0
        private void StartToInvokeFunction()
        {
            var cts = new CancellationToken();

            Task.Factory.StartNew(async() =>
            {
                while (ActionQueue.Any())
                {
                    ActionQueue.TryDequeue(out Action action);
                    await Task.Factory.StartNew(action, cts);
                    await Task.Delay(100, cts);
                }
                _runingAction = false;
            }, cts);
            TaskCompleted?.Invoke(this, EventArgs.Empty);
        }
Пример #24
0
        //-------------------------------------------------------------------------------
        /// <summary>
        /// overloaded: Creates a task.
        /// </summary>
        /// <typeparam name="T">data type.</typeparam>
        /// <param name="taskCompletedCallBack"> callback upon complete.</param>
        /// <param name="userData">user data to be used in task.</param>
        /// <param name="task">thread</param>
        /// <param name="bContinuousExecution">if allow continuous execution.</param>
        /// <returns></returns>
        //-------------------------------------------------------------------------------
        public TaskHandle CreateTask <T>(TaskCompleted taskCompletedCallBack, object userData, ParameterizedThreadStart task, bool bContinuousExecution)
        {
            Task <T> theTask = new Task <T>(taskCompletedCallBack, userData, task, bContinuousExecution);

            theTask.Name = "Task " + m_nTaskCount;
            TaskHandle taskHandle = new TaskHandle(m_nTaskCount++);

            theTask.Handle = taskHandle;

            m_dictionaryLock.TryEnterWriteLock(5);
            {
                m_tasks.Add(taskHandle, theTask);
            }
            m_dictionaryLock.ExitWriteLock();

            return(taskHandle);
        }
Пример #25
0
        public async Task <TaskCompleted> SaveTaskCompleted(TaskCompleted taskCompleted)
        {
            try
            {
                taskCompleted.LastUpdatedDate = DateTime.Now;
                taskCompleted.LastUpdatedBy   = _userManager.CurrentUser();

                var savedTaskCompleted = _unitOfWork.TaskCompeletedRepository.Add(taskCompleted);
                await _unitOfWork.SaveChangesAsync();

                return(savedTaskCompleted);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #26
0
        public void Handle(TaskCompleted <PhotoResult> result)
        {
            if (result.Result.TaskResult == TaskResult.OK)
            {
                byte[] bytes;
                var    sourceStream = result.Result.ChosenPhoto;
                var    fileName     = result.Result.OriginalFileName;
                using (var memoryStream = new MemoryStream())
                {
                    sourceStream.CopyTo(memoryStream);
                    bytes = memoryStream.ToArray();
                }

                StateService.ProfilePhotoBytes = bytes;
                PhotoBytes = bytes;
                NotifyOfPropertyChange(() => PhotoBytes);
            }
        }
Пример #27
0
        //----------------------------------------------------------------------------------
        //----------------------------------------------------------------------------------
        private bool IsChunkAlreadyLoaded(String szAssetGroupName, TaskCompleted callback)
        {
            bool bIsLoaded = false;

            if (m_loadedAssets.ContainsKey(szAssetGroupName.GetHashCode()))
            {
                Asset asset = m_loadedAssets[szAssetGroupName.GetHashCode()];
                asset.RefCount++;

                if (callback != null)
                {
                    callback(asset);
                }

                bIsLoaded = true;
            }

            return(bIsLoaded);
        }
Пример #28
0
        /// <summary>
        ///		Called to notify task controller that a task has been completed.
        /// </summary>
        /// <param name="taskCompleted">
        ///		The <see cref="TaskCompleted"/> notification message.
        /// </param>
        void OnTaskCompleted(TaskCompleted taskCompleted)
        {
            if (taskCompleted == null)
            {
                throw new ArgumentNullException("taskCompleted");
            }

            Log.Information(
                "{ActorPath}: Task completed by task-runner '{TaskRunnerName}' in {RunTime}: {What} ({TotalTaskCount} tasks now active)",
                Self.Path.ToUserRelativePath(),
                taskCompleted.ByWho,
                taskCompleted.RunTime,
                taskCompleted.What,
                --_outstandingTaskCount
                );

            if (_shutdownPending)
            {
                StopIfAllRequestsComplete();
            }
        }
Пример #29
0
        public MainWindow()
        {
            Window = this;

            InitializeComponent();
            InitComponents();

            var musicDir = Properties.Settings.Default.MusicDir.Trim();

            if (string.IsNullOrEmpty(musicDir))
            {
                musicDir = Properties.Settings.Default.DefaultMusicDir.Trim();
            }
            MusicDirTextBox.Text = musicDir;

            AddLyricForAllRadioButton.IsChecked = true;

            _lyricAdder = new LyricAdder();

            _taskCompleted = InitComponents;
        }
Пример #30
0
        private void Handle(TaskCompleted message)
        {
            RequireActivation(true);
            if (message.ParentTaskInstanceId != this.InstanceId)
            {
                throw new Exception();
            }
            if (message is MultiTaskCompleted)
            {
                throw new Exception();
            }
            TransitionInfo ti = GetTransition(message.FromTaskInstanceId);

            if (ti == null)
            {
                throw new Exception();
            }
            log.Info("MT Child task {0} has completed", ti.InstanceId);
            if (ti.Status == TransitionStatus.Completed)
            {
                return;
            }
            if (!ti.IsTransitionActive)
            {
                log.Warn("Transition {0} ({1}) is not active: {2}", ti.InstanceId, ti.TaskId, ti.Status);
                return;
            }
            ti.Status     = TransitionStatus.Completed;
            ti.OutputData = message.OutputData;
            if (ti.OutputData == null)
            {
                log.Info("No output data returned from child task {0}", ti.InstanceId);
                ti.OutputData = new Dictionary <string, object>();
            }
            OnTransitionStatusChanged(ti.InstanceId);
            return;
        }
Пример #31
0
        /// <summary>
        /// Add a <see cref="TaskCompleted"/> callback
        /// </summary>
        /// <param name="callback"><see cref="TaskCompleted"/> callback to add</param>
        /// <returns>The <see cref="TaskContext"/></returns>
        public TaskContext Completed(TaskCompleted callback)
        {
            if (IsComplete) callback(this);

            _completed += callback;
            return this;
        }
Пример #32
0
 public bool Poll(out TaskCompleted completed)
 {
     return _completeds.TryTake(out completed);
 }
Пример #33
0
 public void OfferAndWaitUntilAccepted(TaskCompleted completed)
 {
     _completeds.Add(completed);
 }
Пример #34
0
 public bool Offer(TaskCompleted completed)
 {
     return _completeds.TryAdd(completed);
 }
Пример #35
0
        /// <summary>
        ///		Called to notify task controller that a task has been completed.
        /// </summary>
        /// <param name="taskCompleted">
        ///		The <see cref="TaskCompleted"/> notification message.
        /// </param>
        void OnTaskCompleted(TaskCompleted taskCompleted)
        {
            if (taskCompleted == null)
                throw new ArgumentNullException("taskCompleted");

            Log.Information(
                "{ActorPath}: Task completed by task-runner '{TaskRunnerName}' in {RunTime}: {What} ({TotalTaskCount} tasks now active)",
                Self.Path.ToUserRelativePath(),
                taskCompleted.ByWho,
                taskCompleted.RunTime,
                taskCompleted.What,
                --_outstandingTaskCount
            );

            if (_shutdownPending)
                StopIfAllRequestsComplete();
        }
Пример #36
0
 public void Process(TaskCompleted completed)
 {
     completed.Send(_socket);
 }