Example #1
0
        public Task DeleteItemAsync()
        {
            // Delete Item with exception handling
            return(RunWithErrorHandling(async() =>
            {
                // Validate
                if (currentList == null)
                {
                    throw new ArgumentNullException("currentList");
                }
                if (currentItem == null)
                {
                    throw new ArgumentNullException("currentItem");
                }

                // Get index of current Item
                var index = currentList.Items.IndexOf(currentItem);

                // Find out previous but bound to 0
                index = Math.Max(index - 1, 0);

                // Remove from the list
                currentList.Items.Remove(currentItem);

                // Save the list
                await todoService.SaveAsync(currentList);

                // Set current Item to the next closest one
                if (currentList.Items.Count > index)
                {
                    CurrentItem = currentList.Items[index];
                }
            }
                                        , TaskRunOptions.WithFailure(string.Format("Could not delete {0}", currentItem.Title))));
        }
Example #2
0
        internal static ITaskRunner GetTaskRunnerUnchecked(Component component, TaskRunOptions options)
        {
            var owner = component.gameObject;

            // Apply the global configuration to the options.
            options = Config.Apply(options);

            // Check if there is a existing runner for the same scope.
            owner.GetComponents <MonoBehaviourTaskRunner>(monoBehaviourRunners);
            foreach (var runner in monoBehaviourRunners)
            {
                // If there is a runner for that component then return that.
                if (runner.RunOptions == options && object.ReferenceEquals(runner.ComponentToFollow, component))
                {
                    return(runner);
                }
            }

            // Otherwise create a new runner for this component.
            var newRunner = owner.AddComponent <MonoBehaviourTaskRunner>();

            newRunner.RunOptions        = options;
            newRunner.ComponentToFollow = component;
            newRunner.hideFlags         = HideFlags.HideInInspector;
            return(newRunner);
        }
Example #3
0
        public Task DeleteListAsync()
        {
            // Delete list with exception handling
            return(RunWithErrorHandling(async() =>
            {
                // Validate
                if (currentList == null)
                {
                    throw new ArgumentNullException("currentList");
                }

                // Get index of current list
                var index = lists.IndexOf(currentList);

                // Find out previous but bound to 0
                index = Math.Max(index - 1, 0);

                // Attempt to delete current list
                await todoService.DeleteAsync(currentList);

                // Delete successful so remove from lists collection
                lists.Remove(currentList);

                // Set current list to the next closest one
                if (lists.Count > index)
                {
                    CurrentList = lists[index];
                }
            }
                                        , TaskRunOptions.WithFailure(string.Format("Could not delete {0} list", currentList.Title))));
        }
Example #4
0
 public static ITask Then(this ITask task, Action <bool> continuation, TaskRunOptions runOptions = TaskRunOptions.OnSuccess)
 {
     Guard.ArgumentNotNull(continuation, "continuation");
     return(task.Then(new ActionTask(task.Token, continuation)
     {
         Name = "Then"
     }, runOptions));
 }
Example #5
0
        /// <summary>
        /// Modify run-options based on the global config.
        /// </summary>
        /// <param name="options">Options to modify.</param>
        /// <returns>Modified options.</returns>
        internal static TaskRunOptions Apply(TaskRunOptions options)
        {
            if (GlobalDiagnosticsActive)
            {
                options |= TaskRunOptions.DiagnosticLogging;
            }

            return(options);
        }
        /// <summary>
        /// Assert that current execution is running in the context of the given component.
        /// </summary>
        /// <remarks>
        /// Uses implementation details to assert this behaviour but can be usefull to assert that
        /// sync-context is flowed correctly.
        /// </remarks>
        public static void AssertRunningInComponentContext(
            Component component,
            TaskRunOptions options = TaskRunOptions.Default)
        {
            var currentSyncContext = SynchronizationContext.Current;
            var compSyncContext    = GetComponentSyncContext(component, options);

            Assert.True(
                condition: object.ReferenceEquals(compSyncContext, currentSyncContext),
                message: $"Not running in the context of '{component}'");
        }
Example #7
0
 private void UpdateRunStatus(ScheduleTaskConfigModel taskModel, TaskRunOptions runType)
 {
     try
     {
         DataCenterHelper dataCenter = new DataCenterHelper();
         dataCenter.UpdateRunStatus(runType, taskModel.Id);
     }
     catch (Exception ex)
     {
         LogHelper.LogError(logSource, string.Format("UpdateRunStatus 执行任务{0}异常,id:{1};ex:{2}", taskModel.TaskName, taskModel.Id, ex.ToString()));
     }
 }
Example #8
0
        /// <summary>
        /// Get a <see cref="ITaskRunner"/> for the given component.
        /// </summary>
        /// <remarks>
        /// If a existing runner exists for the component then that is returned, otherwise a new
        /// runner is created.
        ///
        /// Can only be called from the unity-thread in play-mode.
        /// </remarks>
        /// <exception cref="ComponentTask.Exceptions.NotPlayingException">
        /// Thrown when called in edit-mode.
        /// </exception>
        /// <exception cref="ComponentTask.Exceptions.NonUnityThreadException">
        /// Thrown when called from a non-unity thread.
        /// </exception>
        /// <param name="component">Component to get the runner for.</param>
        /// <param name="options">Options for configuring how tasks are run on this runner.</param>
        /// <returns><see cref="ITaskRunner"/> scoped to the given component.</returns>
        public static ITaskRunner GetTaskRunner(
            this Component component,
            TaskRunOptions options = TaskRunOptions.Default)
        {
            // Validate params.
            UnityHelper.ThrowForInvalidObjectParam(component, nameof(component));

            // Validate state.
            UnityHelper.ThrowForNonUnityThreadOrEditMode();

            // Start the task on a runner for the component.
            return(GetTaskRunnerUnchecked(component, options));
        }
Example #9
0
        /// <summary>
        /// Executes a task and handles any errors that occur.
        /// </summary>
        /// <param name="action">
        /// The <see cref="Action"/> to execute.
        /// </param>
        /// <param name="options">
        /// A <see cref="TaskRunOptions"/> instance that specifies options for running the task or <see langword="null"/>
        /// to use <see cref="TaskRunOptions.Default"/>.
        /// </param>
        /// <returns>
        /// A <see cref="Task"/> that represents the wrapped execution of the inner action.
        /// </returns>
        protected async Task RunWithErrorHandling(Action action, TaskRunOptions options = null)
        {
            // Busy?
            if (options.IsBusy)
            {
                isBusy = true;
            }

            // Use task helper
            await TaskHelper.RunWithErrorHandling(action, options);

            // No longer busy?
            if (options.IsBusy)
            {
                isBusy = false;
            }
        }
Example #10
0
 protected override Task LoadDefaultDataAsync()
 {
     // Load data with exception handling
     return(RunWithErrorHandling(async() =>
     {
         Lists = await todoService.LoadListsAsync();
         if (Lists.Count > 0)
         {
             CurrentList = Lists[0];
             if (CurrentList.Items.Count > 0)
             {
                 CurrentItem = CurrentList.Items[0];
             }
         }
     }
                                 , TaskRunOptions.WithFailure("Could not load lists.")));
 }
Example #11
0
        public virtual T Then <T>(T nextTask, TaskRunOptions runOptions = TaskRunOptions.OnSuccess)
            where T : ITask
        {
            Guard.ArgumentNotNull(nextTask, nameof(nextTask));
            var nextTaskBase = ((TaskBase)(object)nextTask);

            // find the task at the top of the chain
            nextTaskBase = nextTaskBase.GetTopMostTask() ?? nextTaskBase;
            // make the next task dependent on this one so it can get values from us
            nextTaskBase.SetDependsOn(this);

            if (runOptions == TaskRunOptions.OnSuccess)
            {
                this.continuationOnSuccess = nextTaskBase;

                // if there are fault handlers in the chain we're appending, propagate them
                // up this chain as well
                if (nextTaskBase.continuationOnFailure != null)
                {
                    SetFaultHandler(nextTaskBase.continuationOnFailure);
                }
                else if (nextTaskBase.continuationOnAlways != null)
                {
                    SetFaultHandler(nextTaskBase.continuationOnAlways);
                }
                if (nextTaskBase.catchHandler != null)
                {
                    Catch(nextTaskBase.catchHandler);
                }
                if (nextTaskBase.finallyHandler != null)
                {
                    Finally(nextTaskBase.finallyHandler);
                }
            }
            else if (runOptions == TaskRunOptions.OnFailure)
            {
                this.continuationOnFailure = nextTaskBase;
                DependsOn?.SetFaultHandler(nextTaskBase);
            }
            else
            {
                this.continuationOnAlways = nextTaskBase;
                DependsOn?.SetFaultHandler(nextTaskBase);
            }
            return(nextTask);
        }
Example #12
0
        /// <summary>
        /// Start a task scoped to the given component.
        /// </summary>
        /// <remarks>
        /// The task will run 'on' the component, meaning that the task gets paused when the component
        /// is disabled and the task will get cancelled when the component is destroyed.
        ///
        /// Can only be called from the unity-thread in play-mode.
        /// </remarks>
        /// <exception cref="ComponentTask.Exceptions.NotPlayingException">
        /// Thrown when called in edit-mode.
        /// </exception>
        /// <exception cref="ComponentTask.Exceptions.NonUnityThreadException">
        /// Thrown when called from a non-unity thread.
        /// </exception>
        /// <exception cref="ComponentTask.Exceptions.TaskCreatorReturnedNullException">
        /// Thrown when null is returned from the 'taskCreator'.
        /// </exception>
        /// <exception cref="ComponentTask.Exceptions.ComponentTaskCanceledException">
        /// Thrown when awaiting a component-task that gets cancelled. Can happen if you are awaiting
        /// a component that gets destroyed.
        /// </exception>
        /// <exception cref="ComponentTask.Exceptions.InactiveGameObjectException">
        /// Thrown when attempting to start a task on a disabled gameobject.
        /// </exception>
        /// <exception cref="ComponentTask.Exceptions.InactiveComponentException">
        /// Thrown when attempting to start a task on a disabled component.
        /// Does not happen when giving <see cref="TaskRunOptions.UpdateWhileComponentDisabled"/> flag.
        /// </exception>
        /// <param name="component">Component to run the task 'on'.</param>
        /// <param name="taskCreator">Function for creating the task.</param>
        /// <param name="options">Options for configuring how the task is run.</param>
        /// <returns>
        /// Task that completes when the original task completes or when the component gets destroyed.
        /// </returns>
        public static Task StartTask(
            this Component component,
            Func <Task> taskCreator,
            TaskRunOptions options = TaskRunOptions.Default)
        {
            // Validate params.
            UnityHelper.ThrowForInvalidObjectParam(component, nameof(component));
            if (taskCreator is null)
            {
                throw new ArgumentNullException(nameof(taskCreator));
            }

            // Validate state.
            UnityHelper.ThrowForNonUnityThreadOrEditMode();

            // Start the task on a runner for the component.
            return(GetTaskRunnerUnchecked(component, options).StartTask(taskCreator));
        }
Example #13
0
        public Task SaveListAsync(TodoList list = null)
        {
            // If null, use current
            if (list == null)
            {
                list = currentList;
            }

            // Save list with exception handling
            if (list != null)
            {
                return(RunWithErrorHandling(() => todoService.SaveAsync(list), TaskRunOptions.WithFailure(string.Format("Could not save {0} list", list.Title))));
            }
            else
            {
                return(TaskHelper.CompletedTask);
            }
        }
Example #14
0
        /// <summary>
        /// Create a <see cref="ITaskRunner"/> on the given gameobject.
        /// </summary>
        /// <remarks>
        /// If you run tasks on the returned runner then they are cancelled automatically when the
        /// gameobject is destroyed.
        ///
        /// Can only be called from the unity-thread in play-mode.
        /// </remarks>
        /// <exception cref="ComponentTask.Exceptions.NotPlayingException">
        /// Thrown when called in edit-mode.
        /// </exception>
        /// <exception cref="ComponentTask.Exceptions.NonUnityThreadException">
        /// Thrown when called from a non-unity thread.
        /// </exception>
        /// <param name="gameObject">GameObject to create the task-runner on.</param>
        /// <param name="options">Options for configuring how tasks are run on this runner.</param>
        /// <returns>Newly created <see cref="ITaskRunner"/>.</returns>
        public static ITaskRunner CreateTaskRunner(
            this GameObject gameObject,
            TaskRunOptions options = TaskRunOptions.Default)
        {
            // Validate params.
            UnityHelper.ThrowForInvalidObjectParam(gameObject, nameof(gameObject));

            // Validate state.
            UnityHelper.ThrowForNonUnityThreadOrEditMode();

            // Create runner.
            var runner = gameObject.AddComponent <MonoBehaviourTaskRunner>();

            runner.RunOptions = Config.Apply(options);
            runner.hideFlags  = HideFlags.HideInInspector;

            return(runner);
        }
        private static SynchronizationContext GetComponentSyncContext(
            Component component,
            TaskRunOptions options)
        {
            /* These are internal implementation details but is usefull to be able to assert
             * that sync-context is flowed correctly. */

            var monoBehaviourRunner = component.GetTaskRunner(options);
            var taskRunnerImpl      = monoBehaviourRunner.
                                      GetType().
                                      GetField("taskRunner", BindingFlags.Instance | BindingFlags.NonPublic).
                                      GetValue(monoBehaviourRunner);
            var context = taskRunnerImpl.
                          GetType().
                          GetField("context", BindingFlags.Instance | BindingFlags.NonPublic).
                          GetValue(taskRunnerImpl);

            return(context as SynchronizationContext);
        }
Example #16
0
 /// <summary>
 /// 更新运行状态
 /// </summary>
 /// <param name="runStatus"></param>
 /// <param name="id"></param>
 /// <returns></returns>
 internal bool UpdateRunStatus(TaskRunOptions runStatus, int id)
 {
     using (SqlConnection connection = new SqlConnection(ConnectionString))
     {
         string commandText = "update  ScheduleTaskConfig set runStatus=@runStatus {0} where id=@id";
         if (runStatus == TaskRunOptions.Runing)
         {
             commandText = string.Format(commandText, ",lastruntime = @lastruntime ");
         }
         else
         {
             commandText = string.Format(commandText, "");
         }
         using (SqlCommand command = new SqlCommand(commandText, connection))
         {
             command.Parameters.Add(new SqlParameter()
             {
                 ParameterName = "@runStatus",
                 SqlDbType     = SqlDbType.Int,
                 Size          = 4,
                 Value         = runStatus
             });
             command.Parameters.Add(new SqlParameter()
             {
                 ParameterName = "@lastruntime",
                 SqlDbType     = SqlDbType.DateTime,
                 Size          = 8,
                 Value         = DateTime.Now
             });
             command.Parameters.Add(new SqlParameter()
             {
                 ParameterName = "@id",
                 SqlDbType     = SqlDbType.Int,
                 Size          = 4,
                 Value         = id
             });
             connection.Open();
             return(command.ExecuteNonQuery() > 0);
         }
     }
 }
Example #17
0
        public static ITask ThenAsync(this ITask task, Func <Task> asyncDelegate, TaskAffinity affinity = TaskAffinity.Concurrent, string name = "ThenAsync", TaskRunOptions runOptions = TaskRunOptions.OnSuccess)
        {
            task.EnsureNotNull(nameof(task));
            asyncDelegate.EnsureNotNull(nameof(asyncDelegate));
            var cont = new TPLTask(task.TaskManager, asyncDelegate, token: task.Token)
            {
                Affinity = affinity, Name = name
            };

            return(task.Then(cont, runOptions));
        }
Example #18
0
 public static ITask Then <T>(this ITask <T> task, Action <T> continuation, TaskAffinity affinity = TaskAffinity.Concurrent, string name = null, TaskRunOptions runOptions = TaskRunOptions.OnSuccess)
 {
     task.EnsureNotNull(nameof(task));
     continuation.EnsureNotNull(nameof(continuation));
     return(task.Then(new ActionTask <T>(task.TaskManager, continuation, token: task.Token)
     {
         Affinity = affinity, Name = name ?? $"Then<{typeof(T)}>"
     }, runOptions));
 }
Example #19
0
 public static ITask <TRet> Then <T, TRet>(this ITask <T> task, Func <bool, Exception, T, TRet> continuation, TaskAffinity affinity = TaskAffinity.Concurrent, string name = null, TaskRunOptions runOptions = TaskRunOptions.OnSuccess)
 {
     task.EnsureNotNull(nameof(task));
     continuation.EnsureNotNull(nameof(continuation));
     return(task.Then(new FuncTask <T, TRet>(task.TaskManager, continuation, token: task.Token)
     {
         Affinity = affinity, Name = name ?? $"ThenFunc<{typeof(T)}, {typeof(TRet)}>"
     }, runOptions));
 }
Example #20
0
 public static ITask ThenInUI(this ITask task, Action continuation, TaskRunOptions runOptions = TaskRunOptions.OnSuccess)
 {
     return(task.Then(continuation, TaskAffinity.UI, runOptions));
 }
Example #21
0
        public virtual T Then <T>(T nextTask, TaskRunOptions runOptions = TaskRunOptions.OnSuccess, bool taskIsTopOfChain = false)
            where T : ITask
        {
            Guard.ArgumentNotNull(nextTask, nameof(nextTask));
            var nextTaskBase = ((TaskBase)(object)nextTask);

            // find the task at the top of the chain
            if (!taskIsTopOfChain)
            {
                nextTaskBase = nextTaskBase.GetTopMostTask() ?? nextTaskBase;
            }
            // make the next task dependent on this one so it can get values from us
            nextTaskBase.SetDependsOn(this);
            var nextTaskFinallyHandler = nextTaskBase.finallyHandler;

            if (runOptions == TaskRunOptions.OnSuccess)
            {
                this.continuationOnSuccess = nextTaskBase;

                // if there are fault handlers in the chain we're appending, propagate them
                // up this chain as well
                if (nextTaskBase.continuationOnFailure != null)
                {
                    SetFaultHandler(nextTaskBase.continuationOnFailure);
                }
                else if (nextTaskBase.continuationOnAlways != null)
                {
                    SetFaultHandler(nextTaskBase.continuationOnAlways);
                }
                if (nextTaskBase.catchHandler != null)
                {
                    Catch(nextTaskBase.catchHandler);
                }
                if (nextTaskFinallyHandler != null)
                {
                    Finally(nextTaskFinallyHandler);
                }
            }
            else if (runOptions == TaskRunOptions.OnFailure)
            {
                this.continuationOnFailure = nextTaskBase;
                DependsOn?.Then(nextTaskBase, TaskRunOptions.OnFailure, true);
            }
            else
            {
                this.continuationOnAlways = nextTaskBase;
                DependsOn?.SetFaultHandler(nextTaskBase);
            }

            // if the current task has a fault handler, attach it to the chain we're appending
            if (finallyHandler != null)
            {
                TaskBase endOfChainTask = (TaskBase)nextTaskBase.GetEndOfChain();
                while (endOfChainTask != this && endOfChainTask != null)
                {
                    endOfChainTask.finallyHandler += finallyHandler;
                    endOfChainTask = endOfChainTask.DependsOn;
                }
            }

            return(nextTask);
        }
Example #22
0
 public static ITask <TRet> Then <T, TRet>(this ITask <T> task, Func <bool, T, TRet> continuation, TaskAffinity affinity = TaskAffinity.Concurrent, TaskRunOptions runOptions = TaskRunOptions.OnSuccess)
 {
     Guard.ArgumentNotNull(continuation, "continuation");
     return(task.Then(new FuncTask <T, TRet>(task.Token, continuation)
     {
         Affinity = affinity, Name = $"Then<{typeof(T)}, {typeof(TRet)}>"
     }, runOptions));
 }
Example #23
0
        public static ITask <T> Then <T>(this ITask task, Task <T> continuation, TaskAffinity affinity = TaskAffinity.Concurrent, TaskRunOptions runOptions = TaskRunOptions.OnSuccess)
        {
            var cont = new TPLTask <T>(continuation)
            {
                Affinity = affinity, Name = $"ThenAsync<{typeof(T)}>"
            };

            return(task.Then(cont, runOptions));
        }
Example #24
0
 public static ITask Then(this ITask task, Action continuation, TaskAffinity affinity = TaskAffinity.Concurrent, TaskRunOptions runOptions = TaskRunOptions.OnSuccess)
 {
     Guard.ArgumentNotNull(continuation, "continuation");
     return(task.Then(new ActionTask(task.Token, _ => continuation())
     {
         Affinity = affinity, Name = "Then"
     }, runOptions));
 }
 public static ITask <T> ThenInUIAsync <T>(this ITask task, Func <Task <T> > continuation, TaskRunOptions runOptions = TaskRunOptions.OnSuccess, string name = null)
 => ThenAsync(task, continuation, TaskAffinity.UI, name ?? $"{nameof(ThenInUIAsync)}<{typeof(T)}>", runOptions);
Example #26
0
        public static ITask <TRet> ThenAsync <T, TRet>(this ITask <T> task, Func <T, Task <TRet> > asyncDelegate, TaskAffinity affinity = TaskAffinity.Concurrent, string name = null, TaskRunOptions runOptions = TaskRunOptions.OnSuccess)
        {
            task.EnsureNotNull(nameof(task));
            asyncDelegate.EnsureNotNull(nameof(asyncDelegate));
            var cont = new TPLTask <T, TRet>(task.TaskManager, asyncDelegate, token: task.Token)
            {
                Affinity = affinity, Name = name ?? $"ThenAsync<{typeof(T)}, {typeof(TRet)}>"
            };

            return(task.Then(cont, runOptions));
        }
 public static ITask ThenInExclusiveAsync(this ITask task, Func <Task> continuation, TaskRunOptions runOptions = TaskRunOptions.OnSuccess, string name = "ThenInExclusiveAsync")
 => ThenAsync(task, continuation, TaskAffinity.Exclusive, name, runOptions);
 public static ITask <TRet> ThenInExclusiveAsync <T, TRet>(this ITask <T> task, Func <T, Task <TRet> > continuation, TaskRunOptions runOptions = TaskRunOptions.OnSuccess, string name = null)
 => ThenAsync(task, continuation, TaskAffinity.Exclusive, name ?? $"{nameof(ThenInExclusiveAsync)}<{typeof(T)}>", runOptions);
Example #29
0
 public static ITask Then(this ITask task, Action <bool, Exception> continuation, TaskAffinity affinity = TaskAffinity.Concurrent, string name = "Then", TaskRunOptions runOptions = TaskRunOptions.OnSuccess)
 {
     task.EnsureNotNull(nameof(task));
     continuation.EnsureNotNull(nameof(continuation));
     return(task.Then(new ActionTask(task.TaskManager, continuation, token: task.Token)
     {
         Affinity = affinity, Name = name
     }, runOptions));
 }
Example #30
0
 public static ITask <TRet> ThenInUI <T, TRet>(this ITask <T> task, Func <bool, T, TRet> continuation, TaskRunOptions runOptions = TaskRunOptions.OnSuccess)
 {
     return(task.Then(continuation, TaskAffinity.UI, runOptions));
 }