bool ContinuationStatusCheck (TaskContinuationOptions kind) { if (kind == TaskContinuationOptions.None) return true; int kindCode = (int) kind; //var status = task.ContinuationAncestor.Status; var status = task.Status; if (kindCode >= ((int) TaskContinuationOptions.NotOnRanToCompletion)) { // Remove other options kind &= ~(TaskContinuationOptions.PreferFairness | TaskContinuationOptions.LongRunning | TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.ExecuteSynchronously); if (status == TaskStatus.Canceled) { if (kind == TaskContinuationOptions.NotOnCanceled) return false; if (kind == TaskContinuationOptions.OnlyOnFaulted) return false; if (kind == TaskContinuationOptions.OnlyOnRanToCompletion) return false; } else if (status == TaskStatus.Faulted) { if (kind == TaskContinuationOptions.NotOnFaulted) return false; if (kind == TaskContinuationOptions.OnlyOnCanceled) return false; if (kind == TaskContinuationOptions.OnlyOnRanToCompletion) return false; } else if (status == TaskStatus.RanToCompletion) { if (kind == TaskContinuationOptions.NotOnRanToCompletion) return false; if (kind == TaskContinuationOptions.OnlyOnFaulted) return false; if (kind == TaskContinuationOptions.OnlyOnCanceled) return false; } } return true; }
public static Task Publish(this Task task, TaskCompletionSource <object> tcs, TaskContinuationOptions continuationOptions = TaskContinuationOptions.PreferFairness) { task.ContinueWith( (t, o) => { var s = (TaskCompletionSource <object>)o; switch (t.Status) { case TaskStatus.Canceled: s.TrySetCanceled(); break; case TaskStatus.RanToCompletion: s.TrySetResult(null); break; case TaskStatus.Faulted: s.TrySetException(t.Exception.InnerExceptions); break; } }, tcs, continuationOptions ); return(tcs.Task); }
public Task <TNewResult> ContinueWith <TNewResult>(Func <Task <TResult>, object, TNewResult> continuationFunction, object state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { throw new NotImplementedException(); }
public Task ContinueWith(Action <Task <TResult> > continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { throw new NotImplementedException(); }
public TaskFactory(TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions) : this(CancellationToken.None, creationOptions, continuationOptions, null) { }
/// <summary> /// Creates a cancellation token that is canceled when the provided <see cref="Task"/> completes. /// </summary> /// <param name="source">The task to observe.</param> /// <param name="continuationOptions">The options to use for the task continuation.</param> public static NormalizedCancellationToken FromTask(Task source, TaskContinuationOptions continuationOptions) { var cts = new CancellationTokenSource(); source.ContinueWith(_ => cts.Cancel(), CancellationToken.None, continuationOptions, TaskScheduler.Default); return new NormalizedCancellationToken(cts); }
private LimitedConcurrencyTaskFactory(TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions) : base(creationOptions, continuationOptions) { }
public Task ContinueWhenAny(Task[] tasks, Action <Task> continuationAction, TaskContinuationOptions continuationOptions) { return(ContinueWhenAny(tasks, continuationAction, cancellationToken, continuationOptions, GetScheduler())); }
/// <summary> /// Continues the task with a coroutine. /// </summary> /// <returns> /// The continued task. /// </returns> /// <param name='task'> /// Task to continue. /// </param> /// <param name='instruction'> /// The instruction to continue with. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <param name='continuationOptions'> /// Continuation options. /// </param> /// <param name='scheduler'> /// Scheduler to use when scheduling the task. /// </param> public static Task ContinueWith(this Task task, FiberInstruction instruction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (instruction == null) throw new ArgumentNullException ("instruction"); if (scheduler == null) throw new ArgumentNullException ("scheduler"); if (!(scheduler is FiberTaskScheduler)) throw new ArgumentException ("The scheduler for a YieldableTask must be a FiberTaskScheduler", "scheduler"); // This creates a continuation that runs on the default scheduler (e.g. ThreadPool) // where it's OK to wait on a child task to complete. The child task is scheduled // on the given scheduler and attached to the parent. //var outerScheduler = TaskScheduler.Current; //if(outerScheduler is MonoBehaviourTaskScheduler) // outerScheduler = TaskScheduler.Default; var outerScheduler = TaskScheduler.Default; return task.ContinueWith((Task antecedent) => { var yieldableTask = new YieldableTask(instruction, cancellationToken, TaskCreationOptions.AttachedToParent); yieldableTask.Start(scheduler); }, cancellationToken, continuationOptions, outerScheduler); }
/// <summary> /// Continues the task with a coroutine. /// </summary> /// <returns> /// The continued task. /// </returns> /// <param name='task'> /// Task to continue. /// </param> /// <param name='coroutine'> /// The coroutine to continue with. /// </param> /// <param name='continuationOptions'> /// Continuation options. /// </param> public static Task ContinueWith(this Task task, IEnumerator coroutine, TaskContinuationOptions continuationOptions) { return ContinueWith (task, coroutine, CancellationToken.None, continuationOptions, TaskScheduler.Current); }
/// <summary> /// Continues the task with a coroutine. /// </summary> /// <returns> /// The continued task. /// </returns> /// <param name='task'> /// Task to continue. /// </param> /// <param name='instruction'> /// The instruction to continue with. /// </param> /// <param name='continuationOptions'> /// Continuation options. /// </param> public static Task ContinueWith(this Task task, FiberInstruction instruction, TaskContinuationOptions continuationOptions) { return ContinueWith (task, instruction, CancellationToken.None, continuationOptions, TaskScheduler.Current); }
public async void Cannot_Proceed_Past_Timeout() { var logger = new ConsoleLogger(); Guid emuId = Guid.NewGuid(); // Start an emulator. var adbFactory = new AndroidDebugBridgeFactory(TestConfig.PathToAdbExe); int consolePort = 5554; var emuFactory = new AndroidSdkEmulatorFactory(logger, TestConfig.PathToAndroidEmulatorExe, adbFactory, TestConfig.AvdName, consolePort, true, false, emuId); try { using (IEmulator droidEmulator = emuFactory.GetEmulator()) { TaskContinuationOptions y = new TaskContinuationOptions(); await droidEmulator.Start(TimeSpan.FromSeconds(5)).ContinueWith((t) => { if (!t.IsFaulted) { Assert.Fail(); } var exception = t.Exception.InnerExceptions[0]; throw exception; }); } } catch (AggregateException e) { var ex = e.InnerExceptions[0]; throw ex; } }
// Utility method for RunTaskFactoryTests(). private static void ExerciseTaskFactoryInt(TaskFactory<int> tf, TaskScheduler tmDefault, TaskCreationOptions tcoDefault, CancellationToken tokenDefault, TaskContinuationOptions continuationDefault) { TaskScheduler myTM = TaskScheduler.Default; TaskCreationOptions myTCO = TaskCreationOptions.LongRunning; TaskScheduler tmObserved = null; Task<int> f; // // Helper delegates to make the code shorter. // Action<TaskCreationOptions, TaskCreationOptions, string> TCOchecker = delegate (TaskCreationOptions val1, TaskCreationOptions val2, string failMsg) { if (val1 != val2) { Assert.True(false, string.Format(failMsg)); } }; Action<object, object, string> checker = delegate (object val1, object val2, string failMsg) { if (val1 != val2) { Assert.True(false, string.Format(failMsg)); } }; Action init = delegate { tmObserved = null; }; Func<int> int_delegate = delegate { tmObserved = TaskScheduler.Current; return 10; }; Func<object, int> intState_delegate = delegate (object o) { tmObserved = TaskScheduler.Current; return 10; }; //check Factory properties TCOchecker(tf.CreationOptions, tcoDefault, "ExerciseTaskFactoryInt: > TaskFactory.Scheduler returned wrong CreationOptions"); if (tf.Scheduler != null && tmDefault != tf.Scheduler) { Assert.True(false, string.Format("ExerciseTaskFactoryInt: > TaskFactory.Scheduler is not null and returned wrong scheduler")); } if (tokenDefault != tf.CancellationToken) { Assert.True(false, string.Format("ExerciseTaskFactoryInt: > TaskFactory.CancellationToken returned wrong token")); } if (continuationDefault != tf.ContinuationOptions) { Assert.True(false, string.Format("ExerciseTaskFactoryInt: > TaskFactory.ContinuationOptions returned wrong value")); } // // StartNew(func) // init(); f = tf.StartNew(int_delegate); f.Wait(); checker(tmObserved, tmDefault, "ExerciseTaskFactoryInt: > FAILED StartNew(func). Did not see expected TaskScheduler."); TCOchecker(f.CreationOptions, tcoDefault, "ExerciseTaskFactoryInt: > FAILED StartNew(func). Did not see expected TaskCreationOptions."); // // StartNew(func, options) // init(); f = tf.StartNew(int_delegate, myTCO); f.Wait(); checker(tmObserved, tmDefault, "ExerciseTaskFactoryInt: > FAILED StartNew(func, options). Did not see expected TaskScheduler."); TCOchecker(f.CreationOptions, myTCO, "ExerciseTaskFactoryInt: > FAILED StartNew(func, options). Did not see expected TaskCreationOptions."); // // StartNew(func, CT, options, scheduler) // init(); f = tf.StartNew(int_delegate, CancellationToken.None, myTCO, myTM); f.Wait(); checker(tmObserved, myTM, "ExerciseTaskFactoryInt: > FAILED StartNew(func, options, scheduler). Did not see expected TaskScheduler."); TCOchecker(f.CreationOptions, myTCO, "ExerciseTaskFactoryInt: > FAILED StartNew(func, options, scheduler). Did not see expected TaskCreationOptions."); // // StartNew(func<object>, object) // init(); f = tf.StartNew(intState_delegate, 100); f.Wait(); checker(tmObserved, tmDefault, "ExerciseTaskFactoryInt: > FAILED StartNew(func<object>, object). Did not see expected TaskScheduler."); TCOchecker(f.CreationOptions, tcoDefault, "ExerciseTaskFactoryInt: > FAILED StartNew(func<object>, object). Did not see expected TaskCreationOptions."); // // StartNew(func<object>, object, token) // init(); f = tf.StartNew(intState_delegate, 100, tokenDefault); f.Wait(); checker(tmObserved, tmDefault, "ExerciseTaskFactoryInt: > FAILED StartNew(func<object>, object, token). Did not see expected TaskScheduler."); TCOchecker(f.CreationOptions, tcoDefault, "ExerciseTaskFactoryInt: > FAILED StartNew(func<object>, object, token). Did not see expected TaskCreationOptions."); // // StartNew(func<object>, object, options) // init(); f = tf.StartNew(intState_delegate, 100, myTCO); f.Wait(); checker(tmObserved, tmDefault, "ExerciseTaskFactoryInt: > FAILED StartNew(func<object>, object, options). Did not see expected TaskScheduler."); TCOchecker(f.CreationOptions, myTCO, "ExerciseTaskFactoryInt: > FAILED StartNew(func<object>, object, options). Did not see expected TaskCreationOptions."); // // StartNew(func<object>, object, CT, options, scheduler) // init(); f = tf.StartNew(intState_delegate, 100, CancellationToken.None, myTCO, myTM); f.Wait(); checker(tmObserved, myTM, "ExerciseTaskFactoryInt: > FAILED StartNew(func<object>, object, options, scheduler). Did not see expected TaskScheduler."); TCOchecker(f.CreationOptions, myTCO, "ExerciseTaskFactoryInt: > FAILED StartNew(func<object>, object, options, scheduler). Did not see expected TaskCreationOptions."); }
public static Task ContinueWithState <TResult, TState>(this Task <TResult> task, Action <Task <TResult>, TState> continuationAction, TState state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { return(task.ContinueWith( (t, tupleObject) => { var(closureAction, closureState) = ((Action <Task <TResult>, TState>, TState))tupleObject !; closureAction(t, closureState); }, (continuationAction, state), cancellationToken, continuationOptions, TaskScheduler.Default)); }
private LimitedConcurrencyTaskFactory(System.Threading.CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) : base(cancellationToken, creationOptions, continuationOptions, scheduler) { }
internal static Task ContinueWithPreservedCulture(this Task task, Action <Task> continuationAction, TaskContinuationOptions continuationOptions) { // TODO #if ASPNETCORE50 // The Thread class is not available on WinRT return(task.ContinueWith(continuationAction, continuationOptions)); #else var preservedCulture = SaveCulture(); return(task.ContinueWith(t => RunWithPreservedCulture(preservedCulture, continuationAction, t), continuationOptions)); #endif }
public Task ContinueWith(Action <Task <TResult>, object> continuationAction, object state, TaskContinuationOptions continuationOptions) { return(ContinueWith(continuationAction, state, CancellationToken.None, continuationOptions, TaskScheduler.Current)); }
public Task ContinueWhenAny <TAntecedentResult> (Task <TAntecedentResult>[] tasks, Action <Task <TAntecedentResult> > continuationAction, TaskContinuationOptions continuationOptions) { return(ContinueWhenAny(tasks, continuationAction, cancellationToken, continuationOptions, GetScheduler())); }
public Task <TNewResult> ContinueWith <TNewResult> (Func <Task <TResult>, object, TNewResult> continuationFunction, object state, TaskContinuationOptions continuationOptions) { return(ContinueWith <TNewResult> (continuationFunction, state, CancellationToken.None, continuationOptions, TaskScheduler.Current)); }
// Chains a Task continuation to a Task. public static void RunContinueWithTaskTask_State(TaskContinuationOptions options, bool runNegativeCases = false) { bool ran = false; string stateParam = "test"; //used as a state parametr for the continuation if the useStateParam is true if (runNegativeCases) { RunContinueWithBase_ExceptionCases(options, delegate { ran = false; }, delegate (Task t) { return t.ContinueWith(delegate (Task f, object obj) { Debug.WriteLine("Inside"); ran = true; }, stateParam, options); }, delegate { return ran; }, false ); } else { RunContinueWithBase(options, delegate { ran = false; }, delegate (Task t) { return t.ContinueWith(delegate (Task f, object obj) { Debug.WriteLine("Inside"); ran = true; }, stateParam, options); }, delegate { return ran; }, false ); } }
// Base logic for RunContinueWithXXXYYY() methods public static void RunContinueWithBase( TaskContinuationOptions options, Action initRan, Func <Task, Task> continuationMaker, Func <bool> ranValue, bool taskIsFuture) { Debug.WriteLine(" >> (1) ContinueWith after task finishes Successfully."); { bool expect = (options & TaskContinuationOptions.NotOnRanToCompletion) == 0; Task task; if (taskIsFuture) { task = Task <string> .Factory.StartNew(() => ""); } else { task = Task.Factory.StartNew(delegate { }); } task.Wait(); initRan(); Debug.WriteLine("Init Action Ran"); bool cancel = false; Task cont = continuationMaker(task); try { cont.Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions[0] is TaskCanceledException) { cancel = true; } } Debug.WriteLine("Finished Wait"); if (expect != ranValue() || expect == cancel) { Assert.True(false, string.Format("RunContinueWithBase: >> Failed: continuation didn't run or get canceled when expected: ran = {0}, cancel = {1}", ranValue(), cancel)); } } Debug.WriteLine(" >> (2) ContinueWith before task finishes Successfully."); { bool expect = (options & TaskContinuationOptions.NotOnRanToCompletion) == 0; ManualResetEvent mre = new ManualResetEvent(false); Task task; if (taskIsFuture) { task = Task <string> .Factory.StartNew(() => { mre.WaitOne(); return(""); }); } else { task = Task.Factory.StartNew(delegate { mre.WaitOne(); }); } initRan(); bool cancel = false; Task cont = continuationMaker(task); mre.Set(); task.Wait(); try { cont.Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions[0] is TaskCanceledException) { cancel = true; } } if (expect != ranValue() || expect == cancel) { Assert.True(false, string.Format("RunContinueWithBase: >> Failed: continuation didn't run or get canceled when expected: ran = {0}, cancel = {1}", ranValue(), cancel)); } } }
public TaskContinuation (Task task, TaskContinuationOptions continuationOptions) { this.task = task; this.continuationOptions = continuationOptions; }
// Base logic for RunContinueWithXXXYYY() methods public static void RunContinueWithBase_ExceptionCases( TaskContinuationOptions options, Action initRan, Func <Task, Task> continuationMaker, Func <bool> ranValue, bool taskIsFuture) { Debug.WriteLine(" >> (3) ContinueWith after task finishes Exceptionally."); { bool expect = (options & TaskContinuationOptions.NotOnFaulted) == 0; Task task; if (taskIsFuture) { task = Task <string> .Factory.StartNew(delegate { throw new Exception("Boom"); }); } else { task = Task.Factory.StartNew(delegate { throw new Exception("Boom"); }); } try { task.Wait(); } catch (AggregateException) { /*swallow(ouch)*/ } Debug.WriteLine("S3 caught e1."); initRan(); bool cancel = false; Task cont = continuationMaker(task); try { cont.Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions[0] is TaskCanceledException) { cancel = true; } } Debug.WriteLine("S3 finished wait"); if (expect != ranValue() || expect == cancel) { Assert.True(false, string.Format("RunContinueWithBase: >> Failed: continuation didn't run or get canceled when expected: ran = {0}, cancel = {1}", ranValue(), cancel)); } } Debug.WriteLine(" >> (4) ContinueWith before task finishes Exceptionally."); { bool expect = (options & TaskContinuationOptions.NotOnFaulted) == 0; ManualResetEvent mre = new ManualResetEvent(false); Task task; if (taskIsFuture) { task = Task <string> .Factory.StartNew(delegate { mre.WaitOne(); throw new Exception("Boom"); }); } else { task = Task.Factory.StartNew(delegate { mre.WaitOne(); throw new Exception("Boom"); }); } initRan(); bool cancel = false; Task cont = continuationMaker(task); mre.Set(); try { task.Wait(); } catch (AggregateException) { /*swallow(ouch)*/ } try { cont.Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions[0] is TaskCanceledException) { cancel = true; } } if (expect != ranValue() || expect == cancel) { Assert.True(false, string.Format("RunContinueWithBase: >> Failed: continuation didn't run or get canceled when expected: ran = {0}, cancel = {1}", ranValue(), cancel)); } } Debug.WriteLine(" >> (5) ContinueWith after task becomes Aborted."); { bool expect = (options & TaskContinuationOptions.NotOnCanceled) == 0; // Create a task that will transition into Canceled state CancellationTokenSource cts = new CancellationTokenSource(); Task task; ManualResetEvent cancellationMRE = new ManualResetEvent(false); if (taskIsFuture) { task = Task <string> .Factory.StartNew(() => { cancellationMRE.WaitOne(); throw new OperationCanceledException(cts.Token); }, cts.Token); } else { task = Task.Factory.StartNew(delegate { cancellationMRE.WaitOne(); throw new OperationCanceledException(cts.Token); }, cts.Token); } cts.Cancel(); cancellationMRE.Set(); initRan(); bool cancel = false; Task cont = continuationMaker(task); try { cont.Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions[0] is TaskCanceledException) { cancel = true; } } if (expect != ranValue() || expect == cancel) { Assert.True(false, string.Format("RunContinueWithBase: >> Failed: continuation didn't run or get canceled when expected: ran = {0}, cancel = {1}", ranValue, cancel)); } } Debug.WriteLine(" >> (6) ContinueWith before task becomes Aborted."); { bool expect = (options & TaskContinuationOptions.NotOnCanceled) == 0; // Create a task that will transition into Canceled state Task task; CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; ManualResetEvent cancellationMRE = new ManualResetEvent(false); if (taskIsFuture) { task = Task <string> .Factory.StartNew(() => { cancellationMRE.WaitOne(); throw new OperationCanceledException(ct); }, ct); } else { task = Task.Factory.StartNew(delegate { cancellationMRE.WaitOne(); throw new OperationCanceledException(ct); }, ct); } initRan(); bool cancel = false; Task cont = continuationMaker(task); cts.Cancel(); cancellationMRE.Set(); try { cont.Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions[0] is TaskCanceledException) { cancel = true; } } if (expect != ranValue() || expect == cancel) { Assert.True(false, string.Format("RunContinueWithBase: >> Failed: continuation didn't run or get canceled when expected: ran = {0}, cancel = {1}", ranValue(), cancel)); } } }
public TaskFactory(CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { this.cancellationToken = cancellationToken; this.scheduler = scheduler; this.creationOptions = creationOptions; this.continuationOptions = continuationOptions; TaskFactory.CheckContinuationOptions(continuationOptions); this.parent = new TaskFactory(cancellationToken, creationOptions, continuationOptions, scheduler); }
/// <summary>Initializes a new continuation.</summary> /// <param name="task">The task to be activated.</param> /// <param name="options">The continuation options.</param> /// <param name="scheduler">The scheduler to use for the continuation.</param> internal StandardTaskContinuation(Task task, TaskContinuationOptions options, TaskScheduler scheduler) { Task = task; Options = options; _scheduler = scheduler; }
public Task ContinueWith(Action<Task> continuationAction, TaskContinuationOptions continuationOptions) { return HandleContinuationTask(_factory.ContinuationTask(this, continuationAction), continuationOptions); }
/// <summary>Invokes the continuation for the target completion task.</summary> /// <param name="completedTask">The completed task.</param> /// <param name="canInlineContinuationTask">Whether the continuation can be inlined.</param> internal override void Run(Task completedTask, bool canInlineContinuationTask) { Debug.Assert(completedTask != null); Debug.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed"); Task?continuationTask = m_task; Debug.Assert(continuationTask != null); m_task = null; // Check if the completion status of the task works with the desired // activation criteria of the TaskContinuationOptions. TaskContinuationOptions options = m_options; bool isRightKind = completedTask.IsCompletedSuccessfully ? (options & TaskContinuationOptions.NotOnRanToCompletion) == 0 : (completedTask.IsCanceled ? (options & TaskContinuationOptions.NotOnCanceled) == 0 : (options & TaskContinuationOptions.NotOnFaulted) == 0); // If the completion status is allowed, run the continuation. if (isRightKind) { // If the task was cancel before running (e.g a ContinueWhenAll with a cancelled caancelation token) // we will still flow it to ScheduleAndStart() were it will check the status before running // We check here to avoid faulty logs that contain a join event to an operation that was already set as completed. if (!continuationTask.IsCanceled && TplEventSource.Log.IsEnabled()) { // Log now that we are sure that this continuation is being ran TplEventSource.Log.TraceOperationRelation(continuationTask.Id, CausalityRelation.AssignDelegate); } continuationTask.m_taskScheduler = m_taskScheduler; // Either run directly or just queue it up for execution, depending // on whether synchronous or asynchronous execution is wanted. if (canInlineContinuationTask && // inlining is allowed by the caller (options & TaskContinuationOptions.ExecuteSynchronously) != 0) // synchronous execution was requested by the continuation's creator { InlineIfPossibleOrElseQueue(continuationTask, needsProtection: true); } else { try { continuationTask.ScheduleAndStart(needsProtection: true); } catch (TaskSchedulerException) { // No further action is necessary -- ScheduleAndStart() already transitioned the // task to faulted. But we want to make sure that no exception is thrown from here. } } } else { // Otherwise, the final state of this task does not match the desired continuation activation criteria; cancel it to denote this. Task.ContingentProperties?cp = continuationTask.m_contingentProperties; // no need to volatile read, as we only care about the token, which is only assignable at construction if (cp is null || cp.m_cancellationToken == default) { // With no cancellation token, use an optimized path that doesn't need to account for concurrent completion. // This is primarily valuable for continuations created with TaskContinuationOptions.NotOn* options, where // we'll cancel the continuation if it's not needed. continuationTask.InternalCancelContinueWithInitialState(); }
public Task ContinueWith(Action <Task <TResult> > continuationAction, TaskContinuationOptions continuationOptions) { throw new NotImplementedException(); }
/// <summary>Gets the options to use for continuation tasks.</summary> /// <param name="toInclude">Any options to include in the result.</param> /// <returns>The options to use.</returns> internal static TaskContinuationOptions GetContinuationOptions(TaskContinuationOptions toInclude = TaskContinuationOptions.None) { return(toInclude | TaskContinuationOptions.DenyChildAttach); }
public static Task ContinueWithState <TState>(this Task task, Action <Task, TState> continuationAction, TState state, TaskContinuationOptions continuationOptions) { return(task.ContinueWith( (t, tupleObject) => { var(closureAction, closureState) = ((Action <Task, TState>, TState))tupleObject !; closureAction(t, closureState); }, (continuationAction, state), continuationOptions)); }
static AsyncEnlightenment() { _CreationDenyChildAttach = EnumValue <TaskCreationOptions>("DenyChildAttach") ?? 0; _ContinuationDenyChildAttach = EnumValue <TaskContinuationOptions>("DenyChildAttach") ?? 0; }
private static void DoNextThen <TIn, TOut>(TaskCompletionSource <TOut> tcs, Task <TIn> previousTask, Func <TIn, Task <TOut> > next, TaskContinuationOptions options) { if (previousTask.IsFaulted && previousTask.Exception != null) { SetInnerException(tcs, previousTask.Exception); return; } if (previousTask.IsCanceled) { tcs.TrySetCanceled(); return; } try { next(previousTask.Result).ContinueWith(nextTask => { if (nextTask.IsFaulted && nextTask.Exception != null) { SetInnerException(tcs, nextTask.Exception); return; } if (nextTask.IsCanceled) { tcs.TrySetCanceled(); return; } try { tcs.TrySetResult(nextTask.Result); } catch (Exception ex) { tcs.TrySetException(ex); } }, options); } catch (Exception ex) { tcs.TrySetException(ex); } }
public Task ContinueWith(Action <Task> continuationAction, TaskContinuationOptions continuationOptions) { return(ContinueWith(continuationAction, CancellationToken.None, continuationOptions, TaskScheduler.Current)); }
internal static Task <TResult> ContinueWithPreservedCulture <T, TResult>(this Task <T> task, Func <Task <T>, TResult> continuationAction, TaskContinuationOptions continuationOptions) { #if ASPNETCORE50 // The Thread class is not available on WinRT return(task.ContinueWith(continuationAction, continuationOptions)); #else var preservedCulture = SaveCulture(); return(task.ContinueWith(t => RunWithPreservedCulture(preservedCulture, continuationAction, t), continuationOptions)); #endif }
public Task ContinueWith(Action <Task> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationAction == null) { throw new ArgumentNullException("continuationAction"); } if (scheduler == null) { throw new ArgumentNullException("scheduler"); } Task continuation = new Task(l => continuationAction((Task)l), this, cancellationToken, GetCreationOptions(continuationOptions), this); ContinueWithCore(continuation, continuationOptions, scheduler); return(continuation); }
public Task ContinueWhenAny(Task[] tasks, Action <Task> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { CheckContinueArguments(tasks, continuationAction, continuationOptions, scheduler); var cont = Task.WhenAnyCore(tasks).ContinueWith(TaskActionInvoker.CreateSelected(continuationAction), cancellationToken, continuationOptions, scheduler); return(cont); }
public Task <TResult> ContinueWith <TResult> (Func <Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions) { return(ContinueWith <TResult> (continuationFunction, CancellationToken.None, continuationOptions, TaskScheduler.Current)); }
public Task <TResult> ContinueWhenAny <TResult> (Task[] tasks, Func <Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions) { return(ContinueWhenAny(tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler())); }
internal void ContinueWithCore(Task continuation, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { ContinueWithCore(continuation, continuationOptions, scheduler, null); }
public TestParameters(API api, TaskType taskType, TaskContinuationOptions continuationOptions, bool withCancellation, TaskInfo[] allTasks) { Api = api; TaskType = taskType; ContinuationOptions = continuationOptions; WithCancellation = withCancellation; AllTaskInfos = allTasks; }
bool ContinuationStatusCheck(TaskContinuationOptions kind) { if (kind == TaskContinuationOptions.None) { return(true); } int kindCode = (int)kind; if (kindCode >= ((int)TaskContinuationOptions.NotOnRanToCompletion)) { // Remove other options kind &= ~(TaskContinuationOptions.PreferFairness | TaskContinuationOptions.LongRunning | TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.ExecuteSynchronously); if (status == TaskStatus.Canceled) { if (kind == TaskContinuationOptions.NotOnCanceled) { return(false); } if (kind == TaskContinuationOptions.OnlyOnFaulted) { return(false); } if (kind == TaskContinuationOptions.OnlyOnRanToCompletion) { return(false); } } else if (status == TaskStatus.Faulted) { if (kind == TaskContinuationOptions.NotOnFaulted) { return(false); } if (kind == TaskContinuationOptions.OnlyOnCanceled) { return(false); } if (kind == TaskContinuationOptions.OnlyOnRanToCompletion) { return(false); } } else if (status == TaskStatus.RanToCompletion) { if (kind == TaskContinuationOptions.NotOnRanToCompletion) { return(false); } if (kind == TaskContinuationOptions.OnlyOnFaulted) { return(false); } if (kind == TaskContinuationOptions.OnlyOnCanceled) { return(false); } } } return(true); }
// Chains a Task<U> continuation to a Task<T>, with a Func<Task<T>, U>. public static void RunContinueWithFutureFuture_State(TaskContinuationOptions options, bool runNegativeCases = false) { bool ran = false; Debug.WriteLine("* RunContinueWithFutureFuture_StateA(Object, options={0})", options); string stateParam = "test"; //used as a state parametr for the continuation if the useStateParam is true if (runNegativeCases) { RunContinueWithBase_ExceptionCases(options, delegate { ran = false; }, delegate (Task t) { return t.ContinueWith<int>(delegate (Task f, Object obj) { ran = true; return 5; }, stateParam, options); }, delegate { return ran; }, true ); } else { RunContinueWithBase(options, delegate { ran = false; }, delegate (Task t) { return t.ContinueWith<int>(delegate (Task f, Object obj) { ran = true; return 5; }, stateParam, options); }, delegate { return ran; }, true ); } }
public Task <TResult> ContinueWhenAll <TAntecedentResult> (Task <TAntecedentResult>[] tasks, Func <Task <TAntecedentResult>[], TResult> continuationFunction, TaskContinuationOptions continuationOptions) { return(ContinueWhenAll(tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler())); }
public void Init (TaskContinuationOptions kind, Func<bool> predicate) { Predicate = predicate; Kind = kind; }
public Task <TNewResult> ContinueWith <TNewResult>(Func <Task <TResult>, object, TNewResult> continuationFunction, object state, TaskContinuationOptions continuationOptions) { throw new NotImplementedException(); }
// Utility method for RunTaskFactoryTests(). private static void ExerciseTaskFactoryInt(TaskFactory<int> tf, TaskScheduler tmDefault, TaskCreationOptions tcoDefault, CancellationToken tokenDefault, TaskContinuationOptions continuationDefault) { TaskScheduler myTM = TaskScheduler.Default; TaskCreationOptions myTCO = TaskCreationOptions.LongRunning; TaskScheduler tmObserved = null; Task<int> f; // Helper delegates to make the code shorter. Action init = delegate { tmObserved = null; }; Func<int> int_delegate = delegate { tmObserved = TaskScheduler.Current; return 10; }; Func<object, int> intState_delegate = delegate (object o) { tmObserved = TaskScheduler.Current; return 10; }; //check Factory properties Assert.Equal(tf.CreationOptions, tcoDefault); if (tf.Scheduler != null) { Assert.Equal(tmDefault, tf.Scheduler); } Assert.Equal(tokenDefault, tf.CancellationToken); Assert.Equal(continuationDefault, tf.ContinuationOptions); // // StartNew(func) // init(); f = tf.StartNew(int_delegate); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, tcoDefault); // // StartNew(func, options) // init(); f = tf.StartNew(int_delegate, myTCO); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, myTCO); // // StartNew(func, CT, options, scheduler) // init(); f = tf.StartNew(int_delegate, CancellationToken.None, myTCO, myTM); f.Wait(); Assert.Equal(tmObserved, myTM); Assert.Equal(f.CreationOptions, myTCO); // // StartNew(func<object>, object) // init(); f = tf.StartNew(intState_delegate, 100); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, tcoDefault); // // StartNew(func<object>, object, token) // init(); f = tf.StartNew(intState_delegate, 100, tokenDefault); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, tcoDefault); // // StartNew(func<object>, object, options) // init(); f = tf.StartNew(intState_delegate, 100, myTCO); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, myTCO); // // StartNew(func<object>, object, CT, options, scheduler) // init(); f = tf.StartNew(intState_delegate, 100, CancellationToken.None, myTCO, myTM); f.Wait(); Assert.Equal(tmObserved, myTM); Assert.Equal(f.CreationOptions, myTCO); }
// Base logic for RunContinueWithXXXYYY() methods public static void RunContinueWithBase_NegativeCases( TaskContinuationOptions options, Action initRan, Func<Task, Task> continuationMaker, Func<bool> ranValue, bool taskIsFuture) { Debug.WriteLine(" >> (3) ContinueWith after task finishes Exceptionally."); { bool expect = (options & TaskContinuationOptions.NotOnFaulted) == 0; Task task; if (taskIsFuture) task = Task<string>.Factory.StartNew(delegate { throw new Exception("Boom"); }); else task = Task.Factory.StartNew(delegate { throw new Exception("Boom"); }); try { task.Wait(); } catch (AggregateException) { /*swallow(ouch)*/ } initRan(); bool cancel = false; Task cont = continuationMaker(task); try { cont.Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions[0] is TaskCanceledException) cancel = true; } if (expect != ranValue() || expect == cancel) { Assert.True(false, string.Format("RunContinueWithBase: >> Failed: continuation didn't run or get canceled when expected: ran = {0}, cancel = {1}", ranValue(), cancel)); } } Debug.WriteLine(" >> (4) ContinueWith before task finishes Exceptionally."); { bool expect = (options & TaskContinuationOptions.NotOnFaulted) == 0; ManualResetEvent mre = new ManualResetEvent(false); Task task; if (taskIsFuture) task = Task<string>.Factory.StartNew(delegate { mre.WaitOne(); throw new Exception("Boom"); }); else task = Task.Factory.StartNew(delegate { mre.WaitOne(); throw new Exception("Boom"); }); initRan(); bool cancel = false; Task cont = continuationMaker(task); mre.Set(); try { task.Wait(); } catch (AggregateException) { /*swallow(ouch)*/ } try { cont.Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions[0] is TaskCanceledException) cancel = true; } if (expect != ranValue() || expect == cancel) { Assert.True(false, string.Format("RunContinueWithBase: >> Failed: continuation didn't run or get canceled when expected: ran = {0}, cancel = {1}", ranValue(), cancel)); } } Debug.WriteLine(" >> (5) ContinueWith after task becomes Aborted."); { bool expect = (options & TaskContinuationOptions.NotOnCanceled) == 0; // Create a task that will transition into Canceled state CancellationTokenSource cts = new CancellationTokenSource(); Task task; ManualResetEvent cancellationMRE = new ManualResetEvent(false); if (taskIsFuture) task = Task<string>.Factory.StartNew(() => { cancellationMRE.WaitOne(); throw new OperationCanceledException(cts.Token); }, cts.Token); else task = Task.Factory.StartNew(delegate { cancellationMRE.WaitOne(); throw new OperationCanceledException(cts.Token); }, cts.Token); cts.Cancel(); cancellationMRE.Set(); initRan(); bool cancel = false; Task cont = continuationMaker(task); try { cont.Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions[0] is TaskCanceledException) cancel = true; } if (expect != ranValue() || expect == cancel) { Assert.True(false, string.Format("RunContinueWithBase: >> Failed: continuation didn't run or get canceled when expected: ran = {0}, cancel = {1}", ranValue, cancel)); } } //Debug.WriteLine(" >> (6) ContinueWith before task becomes Aborted."); { bool expect = (options & TaskContinuationOptions.NotOnCanceled) == 0; // Create a task that will transition into Canceled state Task task; CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; ManualResetEvent cancellationMRE = new ManualResetEvent(false); if (taskIsFuture) task = Task<string>.Factory.StartNew(() => { cancellationMRE.WaitOne(); throw new OperationCanceledException(ct); }, ct); else task = Task.Factory.StartNew(delegate { cancellationMRE.WaitOne(); throw new OperationCanceledException(ct); }, ct); initRan(); bool cancel = false; Task cont = continuationMaker(task); cts.Cancel(); cancellationMRE.Set(); try { cont.Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions[0] is TaskCanceledException) cancel = true; } if (expect != ranValue() || expect == cancel) { Assert.True(false, string.Format("RunContinueWithBase: >> Failed: continuation didn't run or get canceled when expected: ran = {0}, cancel = {1}", ranValue(), cancel)); } } }
protected Task HandleContinuationTask(Task continuationTask, TaskContinuationOptions continuationOptions) { if (((continuationOptions & TaskContinuationOptions.OnlyOnRanToCompletion) == TaskContinuationOptions.OnlyOnRanToCompletion) || ((continuationOptions & TaskContinuationOptions.NotOnFaulted) == TaskContinuationOptions.NotOnFaulted)) { _completedContinuations.Add(continuationTask); if (_completed) continuationTask.Start(); } else if ((continuationOptions & TaskContinuationOptions.OnlyOnFaulted) == TaskContinuationOptions.OnlyOnFaulted) { _faultedContinuations.Add(continuationTask); if (_faulted) continuationTask.Start(); } else if (continuationOptions == TaskContinuationOptions.None) { _continuations.Add(continuationTask); if (_completed || _faulted) continuationTask.Start(); } else throw new NotImplementedException(); return continuationTask; }
// Base logic for RunContinueWithXXXYYY() methods public static void RunContinueWithBase( TaskContinuationOptions options, Action initRan, Func<Task, Task> continuationMaker, Func<bool> ranValue, bool taskIsFuture) { Debug.WriteLine(" >> (1) ContinueWith after task finishes Successfully."); { bool expect = (options & TaskContinuationOptions.NotOnRanToCompletion) == 0; Task task; if (taskIsFuture) task = Task<string>.Factory.StartNew(() => ""); else task = Task.Factory.StartNew(delegate { }); task.Wait(); initRan(); bool cancel = false; Task cont = continuationMaker(task); try { cont.Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions[0] is TaskCanceledException) cancel = true; } if (expect != ranValue() || expect == cancel) { Assert.True(false, string.Format("RunContinueWithBase: >> Failed: continuation didn't run or get canceled when expected: ran = {0}, cancel = {1}", ranValue(), cancel)); } } Debug.WriteLine(" >> (2) ContinueWith before task finishes Successfully."); { bool expect = (options & TaskContinuationOptions.NotOnRanToCompletion) == 0; ManualResetEvent mre = new ManualResetEvent(false); Task task; if (taskIsFuture) task = Task<string>.Factory.StartNew(() => { mre.WaitOne(); return ""; }); else task = Task.Factory.StartNew(delegate { mre.WaitOne(); }); initRan(); bool cancel = false; Task cont = continuationMaker(task); mre.Set(); task.Wait(); try { cont.Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions[0] is TaskCanceledException) cancel = true; } if (expect != ranValue() || expect == cancel) { Assert.True(false, string.Format("RunContinueWithBase: >> Failed: continuation didn't run or get canceled when expected: ran = {0}, cancel = {1}", ranValue(), cancel)); } } }
// Chains a Task<U> continuation to a Task<T>, with a Func<Task<T>, U>. public static void RunContinueWithFutureFuture(TaskContinuationOptions options, bool runNegativeCases = false) { bool ran = false; if (runNegativeCases) { RunContinueWithBase_NegativeCases(options, delegate { ran = false; }, delegate (Task t) { return t.ContinueWith<int>(delegate (Task f) { ran = true; return 5; }, options); }, delegate { return ran; }, true ); } else { RunContinueWithBase(options, delegate { ran = false; }, delegate (Task t) { return t.ContinueWith<int>(delegate (Task f) { ran = true; return 5; }, options); }, delegate { return ran; }, true ); } }
/// <summary>Initializes a new continuation.</summary> /// <param name="task">The task to be activated.</param> /// <param name="options">The continuation options.</param> /// <param name="scheduler">The scheduler to use for the continuation.</param> internal StandardTaskContinuation(Task task, TaskContinuationOptions options, TaskScheduler scheduler) { Contract.Requires(task != null, "TaskContinuation ctor: task is null"); Contract.Requires(scheduler != null, "TaskContinuation ctor: scheduler is null"); Task = task; Options = options; _scheduler = scheduler; }
private static Task CreateWrappingContinuingTask(Task originalTask, Action<Task> continuationTask, TaskContinuationOptions options) { var continuation = originalTask.ContinueWith(continuationTask, options); var wrapper = new Task(() => { originalTask.Start(); continuation.Wait(); }); return wrapper; }
private Task[] _tasks; // tasks to be continued from #endregion #region Constructor /// <summary> /// Create the test given the parameters /// </summary> public TaskContinueWithAllAnyTest(TestParameters parameters) { _api = parameters.Api; _taskType = parameters.TaskType; _tcOption = parameters.ContinuationOptions; // set up the TaskScheduler under which the contination will be scheduled _tm = TaskScheduler.Default; // create a new cancellation token for each test _cancellationToken = parameters.WithCancellation ? CancellationToken.None : new CancellationToken(); _taskInfos = parameters.AllTaskInfos; _tasks = new Task[parameters.AllTaskInfos.Length]; }