private void AddContinuation(KUITaskBase next)
 {
     // Start a synchronous task, the KUITask will detach if needed
     _task.ContinueWith((prevTask) =>
     {
         next.DoStart(prevTask.Result);
     }, _config.CancellationToken, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled,
                        TaskScheduler.Current);
 }
            public ExecutionConfig(KUITaskBase root)
            {
                this.Root = root;
                Tasks.TryAdd(Root, false);

                // Determine the UI context, creating a new one if required
                if (SynchronizationContext.Current == null)
                {
                    SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
                }
                UIContext = TaskScheduler.FromCurrentSynchronizationContext();

                // Create a cancellation source
                _cancel = new CancellationTokenSource();
            }
            internal Task <ExecutionState> Execute(KUITaskBase task, ExecutionState state)
            {
                Func <ExecutionState> action = () =>
                {
                    ExecutionState result = state;

                    // TODO: do this outside the task. However, that requires returning some kind of task
                    bool execute = true;
                    if ((_options & Options.ErrorOnly) != 0 && !state.HasException)
                    {
                        execute = false;
                    }
                    else if ((_options & Options.SuccessOnly) != 0 && state.HasException)
                    {
                        execute = false;
                    }

                    // Always clean up one busy count when the task finishes
                    int busyCountDiff = -1;
                    if (execute)
                    {
                        int busyCountBefore = state.Config.BusyCount;

                        try
                        {
                            result = _action(state);
                        }
                        catch (Exception e)
                        {
                            result = state.NewException(e);

                            // If there is an exception, restore the busy count
                            busyCountDiff -= state.Config.BusyCount - busyCountBefore;
                        }
                    }

                    state.Config.TaskFinished(task);
                    state.Config.AddBusy(busyCountDiff);
                    return(result);
                };

                return(Task.Factory.StartNew(action, state.Config.CancellationToken, TaskCreationOptions.None, GetContext(state)));
            }
 internal void TaskFinished(KUITaskBase task)
 {
     Tasks.TryUpdate(task, true, false);
 }