Beispiel #1
0
        public void Start()
        {
            lock (_external_lock)
            {
                lock (_thread_flag_lock)
                {
                    //clearing attributed status
                    _upload_thread_flag = _upload_thread_flag & 0xffffff;
                    if ((_upload_thread_flag & (_UPLOAD_THREAD_FLAG_READY | _UPLOAD_THREAD_FLAG_PAUSED)) != 0)
                    {
                        if (_enable_slice_upload)
                        {
                            Tracer.GlobalTracer.TraceInfo("---STARTED---");
                            _upload_thread_flag = (_upload_thread_flag | _UPLOAD_THREAD_FLAG_START_REQUESTED) & ~_UPLOAD_THREAD_FLAG_READY;

                            //_monitor_thread = new Thread(_monitor_thread_callback);
                            //_monitor_thread.IsBackground = true;
                            //_monitor_thread.Name = "Upload monitor";
                            //_monitor_thread.Start();
                            ThreadPool.QueueUserWorkItem(new WaitCallback(_monitor_thread_callback), null);
                        }
                        else
                        {
                            throw new NotImplementedException();
                        }
                    }
                    else
                    {
                        return;
                    }
                }
            }
            try { TaskStarted?.Invoke(this, new EventArgs()); } catch { }
        }
Beispiel #2
0
 private void SetCurrentTask(AIBackupUnitTask task)
 {
     currentTask           = task;
     currentTask.Finished += OnCurrentTaskFinished;
     currentTask.Start();
     TaskStarted?.Invoke(currentTask);
 }
Beispiel #3
0
        private void IterateWorkflow(WorkflowRun <TWfContext> run)
        {
            if (_finish.Exists(precondition => precondition.Met(run.FinishedTasks)))
            {
                WorkflowFinished?.Invoke(this, new WorkflowEventArgs <TWfContext>(run.RunId, run.Context));
                return;
            }

            var tasksToExecute = _tasks.Where(kv => kv.Value.Met(run.FinishedTasks) && !run.HasFinished(kv.Key))
                                 .Select(kv => kv.Key).ToList();

            var anythingFinished = false;

            foreach (var task in tasksToExecute)
            {
                task.Action(run.Context);
                run.StartTask(task);
                TaskStarted?.Invoke(this, new WorkflowTaskEventArgs <TWfContext>(run.RunId, task.TaskId, run.Context));
                if (task.Autocomplete)
                {
                    TaskFinished?.Invoke(this,
                                         new WorkflowTaskEventArgs <TWfContext>(run.RunId, task.TaskId, run.Context));
                    run.FinishTask(task);
                    anythingFinished = true;
                }
            }

            if (anythingFinished)
            {
                IterateWorkflow(run);
            }
        }
Beispiel #4
0
        public void Run(string taskName, string taskDescription, Action <ITaskChanges> taskAction)
        {
            var task = new Task(taskName, taskDescription, taskAction);

            TaskStarted.Raise(this, new TaskEventArgs(task));
            task.Run();
        }
Beispiel #5
0
        public void Update()
        {
            _searchItems.Clear();

            var classNames = ClassNames.ToList();
            var i          = 0;
            var n          = classNames.Count;
            var progress   = new Progress <ProgressInfo>();

            TaskStarted?.Invoke(progress);

            var progressInterface = (IProgress <ProgressInfo>)progress;

            _searchItems.AddRange(
                classNames
                .Select(
                    name => {
                var subKey   = _clsidKey.OpenSubKey(name);
                var regClass = subKey != default ? CreateSearchItem(new RegistryClass(subKey)) : default;
                progressInterface.Report(new ProgressInfo("Load Classes", ++i, n));
                return(regClass);
            }
                    )
                );
            OnPropertyChanged(nameof(Items));
        }
Beispiel #6
0
        /// <summary>
        /// 开始下载任务
        /// </summary>
        public void Start()
        {
            lock (_external_lock)
            {
                lock (_thread_flag_lock)
                {
                    //clear error flag
                    _download_thread_flag = _download_thread_flag & ~_DOWNLOAD_THREAD_FLAG_ERROR;

                    if (((_download_thread_flag & 0xffffff) & (_DOWNLOAD_THREAD_FLAG_READY | _DOWNLOAD_THREAD_FLAG_PAUSED)) != 0)
                    {
                        //Tracer.GlobalTracer.TraceInfo("---STARTED---");
                        _download_thread_flag    = (_download_thread_flag | _DOWNLOAD_THREAD_FLAG_START_REQUESTED) & ~_DOWNLOAD_THREAD_FLAG_READY;
                        _url_fail_to_fetch_count = 0;
                        //_api.GetAccount(_data.AccountID).GetLocateDownloadLinkAsync(_data.Path, _main_url_request_callback);
                        _url_expire_time             = DateTime.Now;
                        _monitor_thread              = new Thread(_monitor_thread_callback);
                        _monitor_thread.Name         = "Download Monitor";
                        _monitor_thread.IsBackground = false;
                        _monitor_thread.Start();
                    }
                }
            }
            try { TaskStarted?.Invoke(this, new EventArgs()); }
            catch { }
        }
Beispiel #7
0
        /// <summary>
        ///     This function controls the button events from UVC.
        ///     This code if not run in background process, will not be able to handle button pressed events when app is suspended.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void systemmediatransportcontrol_ButtonPressed(SystemMediaTransportControls sender,
                                                               SystemMediaTransportControlsButtonPressedEventArgs args)
        {
            switch (args.Button)
            {
            case SystemMediaTransportControlsButton.Play:
                Debug.WriteLine("UVC play button pressed");
                // If music is in paused state, for a period of more than 5 minutes,
                //app will get task cancellation and it cannot run code.
                //However, user can still play music by pressing play via UVC unless a new app comes in clears UVC.
                //When this happens, the task gets re-initialized and that is asynchronous and hence the wait
                if (!_backgroundtaskrunning)
                {
                    var result = TaskStarted.WaitOne(5000);
                    if (!result)
                    {
                        throw new Exception("Background Task didn't initialize in time");
                    }
                    StartPlayback();
                }
                else
                {
                    BackgroundMediaPlayer.Current.Play();
                }
                break;

            case SystemMediaTransportControlsButton.Pause:
                Debug.WriteLine("UVC pause button pressed");
                try
                {
                    BackgroundMediaPlayer.Current.Pause();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                }
                break;

            case SystemMediaTransportControlsButton.Next:
                Debug.WriteLine("UVC next button pressed");
                SkipToNext();
                break;

            case SystemMediaTransportControlsButton.Previous:
                Debug.WriteLine("UVC previous button pressed");
                if (BackgroundMediaPlayer.Current.Position.TotalSeconds > 20)
                {
                    //StartPlayback();
                    BackgroundMediaPlayer.Current.Position = TimeSpan.Zero;
                    BackgroundMediaPlayer.Current.Play();
                }
                else
                {
                    SkipToPrevious();
                }

                break;
            }
        }
Beispiel #8
0
 public void OnTaskStarted(TaskDefinition task)
 {
     TaskStarted?.Invoke(new TaskStartedEvent
     {
         Task      = task,
         Timestamp = DateTimeUtils.Now
     });
 }
Beispiel #9
0
        /// <summary>
        /// Executes the task.
        /// </summary>
        /// <param name="task">The task.</param>
        /// <exception cref="NotImplementedException"></exception>
        public void ExecuteTask(IEngineTask task)
        {
            // Check if task can be executed
            if (!task.CanBeExecuted())
            {
                task.AddMessage($"The task cannot be executed.", MessageSeverity.Error);
                if (task.ParentJob.FailIfAnyTaskHasError)
                {
                    throw new EngineException(logger, $"The task  cannot be executed. This job was aborted.");
                }
                else
                {
                    return;
                }
            }

            // Execute task
            if (TaskStarted != null)
            {
                TaskStarted.Invoke((Guid)task.EntityId, (Guid)task.InstanceID);
            }
            task.Start();

            // Stop task
            task.Stop();


            if (task.HasErrors)
            {
                task.AddMessage($"The task (instance: {task.InstanceID}) was not executed cause one or more errors occurs.", MessageSeverity.Error);
                if (task.ParentJob.FailIfAnyTaskHasError)
                {
                    if (TaskFinished != null)
                    {
                        TaskFinished.Invoke((Guid)task.EntityId, (Guid)task.InstanceID, false);
                    }

                    throw new EngineException(logger, $"The task (instance: {task.InstanceID}) was not executed cause one or more errors occurs. This job was aborted.");
                }
            }
            else if (task.HasWarnings)
            {
                task.AddMessage($"The task (instance: {task.InstanceID}) was executed but one or more warning occurs.", MessageSeverity.Warning);
                if (task.ParentJob.FailIfAnyTaskHasWarning)
                {
                    if (TaskFinished != null)
                    {
                        TaskFinished.Invoke((Guid)task.EntityId, (Guid)task.InstanceID, false);
                    }

                    throw new EngineException(logger, $"The task (instance: {task.InstanceID}) was executed but one or more warning occurs. This job was aborted.");
                }
            }
            if (TaskFinished != null)
            {
                TaskFinished.Invoke((Guid)task.EntityId, (Guid)task.InstanceID, true);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Raise one of the events that is appropriate for the type of the BuildEventArgs
        /// </summary>
        public void Dispatch(BuildEventArgs buildEvent)
        {
            if (buildEvent is BuildMessageEventArgs)
            {
                MessageRaised?.Invoke(null, (BuildMessageEventArgs)buildEvent);
            }
            else if (buildEvent is TaskStartedEventArgs)
            {
                TaskStarted?.Invoke(null, (TaskStartedEventArgs)buildEvent);
            }
            else if (buildEvent is TaskFinishedEventArgs)
            {
                TaskFinished?.Invoke(null, (TaskFinishedEventArgs)buildEvent);
            }
            else if (buildEvent is TargetStartedEventArgs)
            {
                TargetStarted?.Invoke(null, (TargetStartedEventArgs)buildEvent);
            }
            else if (buildEvent is TargetFinishedEventArgs)
            {
                TargetFinished?.Invoke(null, (TargetFinishedEventArgs)buildEvent);
            }
            else if (buildEvent is ProjectStartedEventArgs)
            {
                ProjectStarted?.Invoke(null, (ProjectStartedEventArgs)buildEvent);
            }
            else if (buildEvent is ProjectFinishedEventArgs)
            {
                ProjectFinished?.Invoke(null, (ProjectFinishedEventArgs)buildEvent);
            }
            else if (buildEvent is BuildStartedEventArgs)
            {
                BuildStarted?.Invoke(null, (BuildStartedEventArgs)buildEvent);
            }
            else if (buildEvent is BuildFinishedEventArgs)
            {
                BuildFinished?.Invoke(null, (BuildFinishedEventArgs)buildEvent);
            }
            else if (buildEvent is CustomBuildEventArgs)
            {
                CustomEventRaised?.Invoke(null, (CustomBuildEventArgs)buildEvent);
            }
            else if (buildEvent is BuildStatusEventArgs)
            {
                StatusEventRaised?.Invoke(null, (BuildStatusEventArgs)buildEvent);
            }
            else if (buildEvent is BuildWarningEventArgs)
            {
                WarningRaised?.Invoke(null, (BuildWarningEventArgs)buildEvent);
            }
            else if (buildEvent is BuildErrorEventArgs)
            {
                ErrorRaised?.Invoke(null, (BuildErrorEventArgs)buildEvent);
            }

            AnyEventRaised?.Invoke(null, buildEvent);
        }
Beispiel #11
0
 public virtual void OnTaskStarted(EventArgs e)
 {
     Collect.Enabled             = NScan.Enabled = false;
     CameraBox.Enabled           = false;
     BeamFlagBox.Objects.Enabled = false;
     Abort.Enabled = Pause.Enabled = true;
     Paused.Set(); // Set running/resumed.
     TaskStarted.Raise(this, e);
 }
        public void OnTaskStarted(EventArgs args)
        {
            groupBoxReadMode.Enabled = false;
            groupBoxSettings.Enabled = false;
            groupBoxTemp.Enabled     = false;
            buttonAbort.Enabled      = true;
            buttonPause.Enabled      = true;
            buttonSave.Enabled       = false;

            Paused.Set(); // set running/resumed
            TaskStarted?.Invoke(this, args);
        }
        private bool StartTask(IScheduledTask scheduledTask)
        {
            lock (_lock)
            {
                if (!IsEnabled)
                {
                    return(false);
                }

                Log.Debug("Starting task {0}", scheduledTask);

                var runningTask = new RunningTask(scheduledTask, _timeService.CurrentDateTime);

#pragma warning disable 4014
                // Note: don't await, we are a scheduler.
                var task = TaskShim.Run(async() => await scheduledTask.InvokeAsync(), runningTask.CancellationTokenSource.Token);
                task.ContinueWith(OnRunningTaskCompleted);
#pragma warning restore 4014

                Log.Debug("Started task {0}", scheduledTask);

                var completed = task.IsCompleted;
                if (completed)
                {
                    // Shortcut mode
                    TaskStarted.SafeInvoke(this, new TaskEventArgs(runningTask));

                    OnRunningTaskCompleted(task);
                }
                else
                {
                    _runningTasks.Add(new RunningTaskInfo(task, runningTask));

                    TaskStarted.SafeInvoke(this, new TaskEventArgs(runningTask));
                }
            }

            // Note: it's important to start possible recurring tasks outside the loop
            if (scheduledTask.Recurring.HasValue)
            {
                var startDate = _timeService.CurrentDateTime.Add(scheduledTask.Recurring.Value);

                Log.Debug("Task {0} is a recurring task, rescheduling a copy at '{1}'", scheduledTask, startDate);

                var newScheduledTask = (IScheduledTask)scheduledTask.Clone();
                newScheduledTask.Start = startDate;

                AddScheduledTask(newScheduledTask);
            }

            return(true);
        }
Beispiel #14
0
        public void StartTask(BuildNode node)
        {
            _logger.LogDebug($"BuildProcess.StartTask: Node: \"{node.Name}\"");
            var task = FindTask(node);

            if (task != null)
            {
                _logger.LogDebug($"BuildProcess.StartTask: Task: {task.GetHashCode()}");
                CurrentTasks.Add(task);
                task.Start();
                TaskStarted?.Invoke(task);
            }
        }
Beispiel #15
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;
        }
Beispiel #16
0
        /// <summary>
        /// Starts new task in current session
        /// </summary>
        /// <param name="context">The task context to start</param>
        private void StartNextTask(TimeTaskContext context)
        {
            // Set provided time
            CurrentTimeLeft = context.SessionDynamicTime;

            // Save it for progress calculations
            mCurrentTask.SessionDynamicTime = CurrentTimeLeft;

            // Start the timer
            mSecondsTicker.Start();

            // Inform subscribers
            TaskStarted.Invoke();
        }
        /// <summary>
        ///		Called to notify task controller that a task has started.
        /// </summary>
        /// <param name="taskStarted">
        ///		The <see cref="TaskStarted"/> notification message.
        /// </param>
        void OnTaskStarted(TaskStarted taskStarted)
        {
            if (taskStarted == null)
            {
                throw new ArgumentNullException("taskStarted");
            }

            Log.Information(
                "{ActorPath}: Task started by task-runner '{TaskRunnerName}': {What} ({TotalTaskCount} tasks now active)",
                Self.Path.ToUserRelativePath(),
                taskStarted.ByWho,
                taskStarted.What,
                _outstandingTaskCount
                );
        }
Beispiel #18
0
        /// <summary>
        ///     The Run method is the entry point of a background task.
        /// </summary>
        /// <param name="taskInstance"></param>
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            _appSettingsHelper = new AppSettingsHelper();
            Debug.WriteLine("Background Audio Task " + taskInstance.Task.Name + " starting...");
            // InitializeAsync SMTC object to talk with UVC.
            //Note that, this is intended to run after app is paused and
            //hence all the logic must be written to run in background process

            _systemmediatransportcontrol = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
            _systemmediatransportcontrol.ButtonPressed += systemmediatransportcontrol_ButtonPressed;
            // _systemmediatransportcontrol.PropertyChanged += systemmediatransportcontrol_PropertyChanged;
            _systemmediatransportcontrol.IsEnabled         = true;
            _systemmediatransportcontrol.IsPauseEnabled    = true;
            _systemmediatransportcontrol.IsPlayEnabled     = true;
            _systemmediatransportcontrol.IsNextEnabled     = true;
            _systemmediatransportcontrol.IsPreviousEnabled = true;



            //InitializeAsync message channel
            BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;
            BackgroundMediaPlayer.Current.CurrentStateChanged   += Current_CurrentStateChanged;

            //Send information to foreground that background task has been started if app is active
            if (ForegroundAppState == ForegroundAppStatus.Active)
            {
                var message = new ValueSet {
                    { PlayerConstants.BackgroundTaskStarted, "" }
                };
                BackgroundMediaPlayer.SendMessageToForeground(message);
            }

            _appSettingsHelper.Write(PlayerConstants.BackgroundTaskState, PlayerConstants.BackgroundTaskRunning);

            // This must be retrieved prior to subscribing to events below which use it
            _deferral = taskInstance.GetDeferral();

            // Mark the background task as started to unblock SMTC Play operation (see related WaitOne on this signal)
            TaskStarted.Set();

            taskInstance.Task.Completed += Taskcompleted;
            taskInstance.Canceled       += OnCanceled;
            //Add handlers for MediaPlayer
            //Add handlers for playlist trackchanged
            QueueManager.TrackChanged += playList_TrackChanged;
            QueueManager.ErrorHandler += QueueManager_ErrorHandler;
            _backgroundtaskrunning     = true;
        }
Beispiel #19
0
        private void StartTask(IScheduledTask scheduledTask)
        {
            Task        task        = null;
            RunningTask runningTask = null;

            lock (_lock)
            {
                if (!IsEnabled)
                {
                    return;
                }

                Log.Debug($"Starting task {scheduledTask}");

                runningTask = new RunningTask(scheduledTask, _timeService.CurrentDateTime);

#pragma warning disable 4014
                // Note: don't await, we are a scheduler
                task = TaskShim.Run(async() => await scheduledTask.InvokeAsync(), runningTask.CancellationTokenSource.Token);
                task.ContinueWith(OnRunningTaskCompleted);
#pragma warning restore 4014

                Log.Debug($"Started task {scheduledTask}");
            }

            if (!scheduledTask.ScheduleRecurringTaskAfterTaskExecutionHasCompleted)
            {
                // Schedule immediately, even though task is still running
                RescheduleRecurringTask(runningTask);
            }

            var completed = task.IsCompleted;
            if (completed)
            {
                // Shortcut mode
                TaskStarted?.Invoke(this, new TaskEventArgs(runningTask));

                OnRunningTaskCompleted(task);
            }
            else
            {
                _runningTasks.Add(new RunningTaskInfo(task, runningTask));

                TaskStarted?.Invoke(this, new TaskEventArgs(runningTask));
            }
        }
Beispiel #20
0
 public RepetitiveTask(Action action, int dueTime, int period)
 {
     State        = RepeririveTaskState.Stopped;
     DueTime      = dueTime;
     Period       = period;
     _action      = action;
     TaskStarted += (task) => State = RepeririveTaskState.TaskStarted;
     TaskEnded   += (task, status) => State = State != RepeririveTaskState.Stopped ? RepeririveTaskState.Waiting : State;
     _timer       = new Timer((sender) =>
     {
         TaskStarted?.Invoke(this);
         Task.Factory.StartNew(action).ContinueWith((task) =>
         {
             TaskEnded?.Invoke(this, task.Status);
         });
     }, null, Timeout.Infinite, Timeout.Infinite);
 }
Beispiel #21
0
        public void Confirm()
        {
            Task.Factory.StartNew(() =>
            {
                try
                {
                    TaskEx.Delay(5000, _cancellationTokenSource.Token).GetAwaiter().GetResult();
                    if (_cancellationTokenSource.IsCancellationRequested)
                    {
                        return;
                    }
                }
                catch (TaskCanceledException)
                {
                    return;
                }

                TaskStarted?.Invoke(this, new DataEventArgs <CreatedNetworkTaskData>(_taskData));
            });
        }
        /// <summary>
        /// Checks the queue for new tasks and pops the next available task
        /// </summary>
        private void PopQueue()
        {
            if (!IsEnabled)
            {
                return;
            }

            lock (_taskQueue)
            {
                Task = null;

                if (!_taskQueue.Any())
                {
                    return;
                }

                Task = _taskQueue[0];
                _taskQueue.RemoveAt(0);
            }

            // Start a thread to execute the task
            _taskFactory.StartNew(() =>
            {
                // Reset values
                IsAbortPending = false;
                TaskStarted?.Invoke(this, new TaskEventArgs(Task));
                ResetStatus();
                Logger.Record($"Executing task {Task.Type} for {Task.ModID}");

                // Execute task
                bool result = ExecuteTask();

                // Reset values
                ResetStatus();
                Logger.Record($"Task executed {(result ? "successfully" : "unsuccessfully")}");
                TaskEnded?.Invoke(this, new TaskEndedEventArgs(Task, result));

                // Pop queue again
                PopQueue();
            });
        }
Beispiel #23
0
        public void RunTask()
        {
            if (!readyToGo)
            {
                throw new ArgumentException("Not ready to go!");
            }
            else
            {
                if (TaskStarted != null)
                {
                    TaskStarted.Invoke(this, new EventArgs());
                }
            }

            Active = true;

            Status = "Analyzing source";

            var urlGen = SetupTask();

            var urls = urlGen.Get(0, NumberToDownload);

            using (repo = new Repository()) {
                // pass on the events
                repo.DownloadFileCompleted += OnSingleDownloadCompleted;

                repo.DownloadProgressChanged += OnDownloadProgressChanged;

                repo.MultipleDownloadsCompleted += OnMultipleDownloadsCompleted;

                // set number downloaded to zero
                NumberDownloaded = 0;

                // begin (blocks)
                repo.Download(urls);
                // repo.Active is set and unset automatically
            }
        }
Beispiel #24
0
 /// <summary>
 /// 启动服务
 /// </summary>
 public async Task Start()
 {
     cts = new CancellationTokenSource();
     await Task.Run(() =>
     {
         int times = 0;
         TaskStarted?.Invoke(this, new TaskEventArgs(TaskName));
         while (!cts.Token.IsCancellationRequested)
         {
             times++;
             if (times *Interval >= TaskCheckInterval)
             {
                 Log.Information($"{TaskName}正在运行");
                 times = 0;
             }
             Repository = new AppRepository();
             lastTime   = DateTime.Now;
             try
             {
                 Run();
             }
             catch (Exception ex)
             {
                 Log.Error(ex, $"{TaskName}抛出异常");
             }
             try
             {
                 Task.Delay(Interval).Wait(cts.Token);
             }
             catch (OperationCanceledException)
             {
             }
         }
         Log.Warning($"{TaskName}已取消");
         TaskStopped?.Invoke(this, new TaskEventArgs(TaskName));
     }, cts.Token);
 }
Beispiel #25
0
        /// <summary>
        ///     Handles background task cancellation. Task cancellation happens due to :
        ///     1. Another Media app comes into foreground and starts playing music
        ///     2. Resource pressure. Your task is consuming more CPU and memory than allowed.
        ///     In either case, save state so that if foreground app resumes it can know where to start.
        /// </summary>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            // You get some time here to save your state before process and resources are reclaimed
            Debug.WriteLine("MyBackgroundAudioTask " + sender.Task.TaskId + " Cancel Requested...");
            try
            {
                TaskStarted.Reset();
                if (_queueManager != null)
                {
                    QueueManager.TrackChanged -= playList_TrackChanged;
                    _queueManager              = null;
                }

                _appSettingsHelper.Write(PlayerConstants.BackgroundTaskState,
                                         PlayerConstants.BackgroundTaskCancelled);

                _backgroundtaskrunning = false;
                //unsubscribe event handlers
                _systemmediatransportcontrol.ButtonPressed -= systemmediatransportcontrol_ButtonPressed;

                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            if (_deferral != null)
            {
                _deferral.Complete(); // signals task completion.
                Debug.WriteLine("AudioPlayer Cancel complete...");
            }

            QueueManager.ErrorHandler -= QueueManager_ErrorHandler;
            TileUpdateManager.CreateTileUpdaterForApplication("App").Clear();
        }
Beispiel #26
0
        private async Task TaskLoop(CancellationToken ct)
        {
            try
            {
                while (!ct.IsCancellationRequested)
                {
                    State = NetworkServiceState.Finding;
                    var result = await _netService.WaitForOneConnection(ct);

                    var connection  = result.Key;
                    var commingType = result.Value;
                    var writer      = new BinaryWriter(connection.GetStream());
                    var reader      = new BinaryReader(connection.GetStream());

                    if (commingType == ConnectionCommingType.FromListen)
                    {
                        var jsontask = reader.ReadString();
                        var task     = JsonConvert.DeserializeObject <CreatedNetworkTaskData>(jsontask);
                        TaskCreated?.Invoke(this, new DataEventArgs <CreatedNetworkTaskData>(task));
                    }
                    else
                    {
                        //todo: generate task...
                        var task = new CreatedNetworkTaskData()
                        {
                            Frequency       = 33100,
                            FrequencyNumber = new Random().Next(0, 10),
                            Id = Guid.NewGuid()
                        };
                        var jsontask = JsonConvert.SerializeObject(task);
                        writer.Write(jsontask);
                        writer.Flush();
                        TaskCreated?.Invoke(this, new DataEventArgs <CreatedNetworkTaskData>(task));
                    }
                    State = NetworkServiceState.RequestForConfirm;

                    var remoteConfirm = TaskEx.Run(() =>
                    {
                        var confirmationResult = reader.ReadString();
                        var isConfirmed        = JsonConvert.DeserializeObject <ConfirmationResult>(confirmationResult);
                        return(isConfirmed);
                    });

                    var localConfirm = _completationConfirm.Task.ContinueWith(t =>
                    {
                        var cjs = JsonConvert.SerializeObject(t.Result);
                        writer.Write(cjs);
                        writer.Flush();
                        return(t.Result);
                    }, TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.NotOnCanceled);

                    var bothConfirmation = await TaskEx.WhenAll(remoteConfirm, localConfirm);

                    bool isBothConfimed = bothConfirmation.All(x => x.Result);
                    if (isBothConfimed)
                    {
                        TaskStarted?.Invoke(this, new DataEventArgs <CreatedNetworkTaskData>());
                    }
                    connection.Close();
                }
            }
            catch (TaskCanceledException) { }
            catch (Exception ex)
            {
                SimpleLogger.Log(ex);
            }
        }
Beispiel #27
0
        internal virtual void ProcessTask(ScheduledTask scheduledTask)
        {
            if (scheduledTask.IsQueued &&
                !scheduledTask.AllowMultipleInstance)
            {
                GlobalConfiguration.Logger.Warn("scheduled task {0} is in queue and not allow multiple instance", scheduledTask.Name);
                return;
            }

            if (!scheduledTask.AllowMultipleInstance)
            {
                if (TasksHost.IsRunning(scheduledTask.Name))
                {
                    GlobalConfiguration.Logger.Warn("scheduled task {0} is already running and not allow multiple instance", scheduledTask.Name);
                    return;
                }
            }

            var id = Guid.NewGuid();

            scheduledTask.IsQueued = true;

            TasksHost.Enqueue(
                id
                , scheduledTask.Name
                , scheduledTask.TaskType
                , scheduledTask.Parameters
                , (dic) =>
            {
                GlobalConfiguration.Logger.Info("scheduled task {0} completed", scheduledTask.Name);
                scheduledTask.IsQueued = false;
                try
                {
                    if (scheduledTask.Completed != null)
                    {
                        scheduledTask.Completed(dic);
                    }
                }
                catch (Exception ex)
                {
                    GlobalConfiguration.Logger.Error(ex);
                }
                finally
                {
                    scheduledTask.IsForced = false;
                    if (scheduledTask.NextRunningDateFactory != null)
                    {
                        try
                        {
                            scheduledTask.NextRunningDate = scheduledTask.NextRunningDateFactory.Invoke();
                        }
                        catch (Exception ex)
                        {
                            GlobalConfiguration.Logger.Error(ex);
                        }
                    }
                }
            }
                , (ex) =>
            {
                scheduledTask.Exception = ex;
                GlobalConfiguration.Logger.Error(ex);
                if (TaskFailed != null)
                {
                    try
                    {
                        TaskFailed.Invoke(scheduledTask.Name, ex);
                    }
                    catch { }
                }
            },
                null,
                () =>
            {
                GlobalConfiguration.Logger.Info("scheduled task {0} started", scheduledTask.Name);
                scheduledTask.StartedCount += 1;
                if (TaskStarted != null)
                {
                    try
                    {
                        TaskStarted.Invoke(scheduledTask.Name);
                    }
                    catch { }
                }
            },
                true,
                scheduledTask.IsForced);
        }
        /// <summary>
        ///		Called to notify task controller that a task has started.
        /// </summary>
        /// <param name="taskStarted">
        ///		The <see cref="TaskStarted"/> notification message.
        /// </param>
        void OnTaskStarted(TaskStarted taskStarted)
        {
            if (taskStarted == null)
                throw new ArgumentNullException("taskStarted");

            Log.Information(
                "{ActorPath}: Task started by task-runner '{TaskRunnerName}': {What} ({TotalTaskCount} tasks now active)",
                Self.Path.ToUserRelativePath(),
                taskStarted.ByWho,
                taskStarted.What,
                _outstandingTaskCount
            );
        }
Beispiel #29
0
 private void Apply(TaskStarted e)
 {
     lastStartTime = e.StartTime;
 }
Beispiel #30
0
 private void RaiseTaskStarted(IBackgroundTask task, object state)
 => TaskStarted?.Invoke(task, state);
 // ReSharper disable once UnusedMember.Local
 private void OnTaskStarted(TaskStartedEventArgs e)
 {
     TaskStarted?.Invoke(this, e);
 }
Beispiel #32
0
 private void TaskRunner_TaskStarted(object sender, EventArgs e)
 {
     TaskStarted?.Invoke(sender, e);
 }