public static Cancellation CreateLinked(Cancellation source) { var cancellation = new Cancellation(); source.RegisterCallback(() => { cancellation.Cancel(); }); return cancellation; }
public void TestCancelStuckEnumerable() { var lastValue = -1; var cancellation = new Cancellation(); var stickWhileEvent = new ManualResetEvent(false); var ints = new DisposableEnumerator<int>(StuckDownEnumerable(stickWhileEvent)); var select = ints .SelectParallely(i => Interlocked.Exchange(ref lastValue, i), cancellation); new Thread(() => { Thread.Sleep(100); cancellation.Cancel(); }).Start(); AssertEx.Throws<OperationCanceledException>(() => select.AsEnumerable().ToList()); Assert.AreEqual(1, lastValue); stickWhileEvent.Set(); Thread.Sleep(100); Assert.IsTrue(ints.IsDisposed); }
public void TestCancel() { bool? cancelled = null; var lastEnumerated = -1; var lastProcessed = -1; var cancellation = new Cancellation(); var endlessSource = Enumerable.Range(0, 10).Select(n => { if (n > 3) TestMonitorSimple.WaitAlittle(); lastEnumerated = n; return n; }); var doForAll = new ForAll<int>(endlessSource, n => Thread.VolatileWrite(ref lastProcessed, n), new ParallelSettings {Cancellation = cancellation}); doForAll.RegisterOnfinished(f => cancelled = f.IsCancelled); doForAll.Start(); TestMonitorSimple.WaitAlittle(); cancellation.Cancel(); TestMonitorSimple.WaitAlittle(); AssertEx.Throws<OperationCanceledException>(() => doForAll.Wait()); Assert.IsTrue(lastProcessed > -1, "Looks like processing had not even started"); Assert.IsTrue(lastEnumerated > -1, "Looks like enumeration of source had not even started"); Assert.IsTrue(cancelled != null && cancelled.Value); Assert.IsTrue(doForAll.IsCancelled); Assert.IsTrue(lastProcessed < 9); Assert.IsTrue(lastEnumerated < 9); }
public void TestSelectParallelCancellation() { var cancellation = new Cancellation(); var maxNumber = 0; var selectResult = Enumerable.Range(0, int.MaxValue).SelectParallely(i => { maxNumber = i; Thread.Sleep(1); return i; }, cancellation); cancellation.Cancel(); AssertEx.Throws<OperationCanceledException>(() => selectResult.AsEnumerable().ToList()); Assert.IsTrue(maxNumber < int.MaxValue-1); }