public void CancellationDoesntResultInEventFiring() { var cts = new CancellationTokenSource(); var oce = new OperationCanceledException(cts.Token); // A Task that throws an exception to cancel var b = new Barrier(2); Task t1 = Task.Factory.StartNew(() => { b.SignalAndWait(); b.SignalAndWait(); throw oce; }, cts.Token); b.SignalAndWait(); // make sure task is started before we cancel cts.Cancel(); b.SignalAndWait(); // release task to complete // This test may be run concurrently with other tests in the suite, // which can be problematic as TaskScheduler.UnobservedTaskException // is global state. The handler is carefully written to be non-problematic // if it happens to be set during the execution of another test that has // an unobserved exception. //EventHandler<UnobservedTaskExceptionEventArgs> handler = // (s, e) => Assert.DoesNotContain(oce, e.Exception.InnerExceptions); //TaskScheduler.UnobservedTaskException += handler; ((IAsyncResult)t1).AsyncWaitHandle.WaitOne(); t1 = null; for (int i = 0; i < 10; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } //TaskScheduler.UnobservedTaskException -= handler; }
public void OperationCanceledException_BasicConstructors() { CancellationToken ct1 = new CancellationTokenSource().Token; OperationCanceledException ex1 = new OperationCanceledException(ct1); Assert.AreEqual(ct1, ex1.CancellationToken); CancellationToken ct2 = new CancellationTokenSource().Token; OperationCanceledException ex2 = new OperationCanceledException("message", ct2); Assert.AreEqual(ct2, ex2.CancellationToken); CancellationToken ct3 = new CancellationTokenSource().Token; OperationCanceledException ex3 = new OperationCanceledException("message", new Exception("inner"), ct3); Assert.AreEqual(ct3, ex3.CancellationToken); }
public void TaskMethodBuilder_Cancellation() { var atmb = AsyncTaskMethodBuilder.Create(); var oce = new OperationCanceledException(); atmb.SetException(oce); var t = atmb.Task; Assert.AreEqual(TaskStatus.Canceled, t.Status); OperationCanceledException caught = AssertExtensions.Throws <OperationCanceledException>(() => { t.GetAwaiter().GetResult(); }); //Assert.AreSame(oce, caught); AssertExtensions.Throws <InvalidOperationException>(() => { atmb.SetResult(); }); AssertExtensions.Throws <InvalidOperationException>(() => { atmb.SetException(new Exception()); }); }