当前位置: 首页>>代码示例>>C#>>正文


C# CancellationTokenSource.Cancel方法代码示例

本文整理汇总了C#中CancellationTokenSource.Cancel方法的典型用法代码示例。如果您正苦于以下问题:C# CancellationTokenSource.Cancel方法的具体用法?C# CancellationTokenSource.Cancel怎么用?C# CancellationTokenSource.Cancel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在CancellationTokenSource的用法示例。


在下文中一共展示了CancellationTokenSource.Cancel方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CancelAfterWait

        public static void CancelAfterWait()
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken cancellationToken = cancellationTokenSource.Token;

            SemaphoreSlim semaphoreSlim = new SemaphoreSlim(0); // semaphore that will block all waiters

            Task.Run(
                () =>
                {
                    for (int i = 0; i < 300; i++) ;
                    cancellationTokenSource.Cancel();
                });

            //Now wait.. the wait should abort and an exception should be thrown
            EnsureOperationCanceledExceptionThrown(
               () => semaphoreSlim.Wait(cancellationToken),
               cancellationToken, "CancelAfterWait:  An OCE(null) should have been thrown that references the cancellationToken.");

            // the token should not have any listeners.
            // currently we don't expose this.. but it was verified manually
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:22,代码来源:SemaphoreSlimCancellationTests.cs

示例2: CreateTestClass

    /// <summary>
    /// Creates an instance of the test class for the given test case. Sends the <see cref="ITestClassConstructionStarting"/>
    /// and <see cref="ITestClassConstructionFinished"/> messages as appropriate.
    /// </summary>
    /// <param name="testCase">The test case</param>
    /// <param name="testClassType">The type of the test class</param>
    /// <param name="constructorArguments">The constructor arguments for the test class</param>
    /// <param name="displayName">The display name of the test case</param>
    /// <param name="messageBus">The message bus used to send the test messages</param>
    /// <param name="timer">The timer used to measure the time taken for construction</param>
    /// <param name="cancellationTokenSource">The cancellation token source</param>
    /// <returns></returns>
    public static object CreateTestClass(this ITestCase testCase,
                                         Type testClassType,
                                         object[] constructorArguments,
                                         string displayName,
                                         IMessageBus messageBus,
                                         ExecutionTimer timer,
                                         CancellationTokenSource cancellationTokenSource)
    {
        object testClass = null;

        if (!messageBus.QueueMessage(new TestClassConstructionStarting(testCase, displayName)))
            cancellationTokenSource.Cancel();

        try
        {
            if (!cancellationTokenSource.IsCancellationRequested)
                timer.Aggregate(() => testClass = Activator.CreateInstance(testClassType, constructorArguments));
        }
        finally
        {
            if (!messageBus.QueueMessage(new TestClassConstructionFinished(testCase, displayName)))
                cancellationTokenSource.Cancel();
        }

        return testClass;
    }
开发者ID:ansarisamer,项目名称:xunit,代码行数:38,代码来源:ReflectionAbstractionExtensions.cs

示例3: CancellationTokenSource

        public void Cancel時にRegisterで登録したデリゲートが呼ばれる()
        {
            var runner = new SampleTaskRunner.TaskRunner();

            {
                // キャンセルしない場合
                var cts = new CancellationTokenSource();
                var t = new Task<string>(c => Cancelで戻り値が切り替わるコルーチン(10, c, cts.Token));
                t.Start(runner);
                runner.Update(20);

                Assert.IsTrue(t.IsCompleted);
                Assert.AreEqual(CompletedMessage, t.Result);
            }

            {
                // キャンセルする場合
                var cts = new CancellationTokenSource();
                var t = new Task<string>(c => Cancelで戻り値が切り替わるコルーチン(10, c, cts.Token));
                t.Start(runner);
                runner.Update(5);
                cts.Cancel();
                runner.Update(5);

                Assert.IsTrue(t.IsCompleted);
                Assert.AreEqual(CanceledMessage, t.Result);
            }
        }
开发者ID:OrangeCubeDev,项目名称:iterator-tasks,代码行数:28,代码来源:CancellationTokenTest.cs

示例4: Main

    static int Main(string[] args)
    {
        SemaphoreSlim s = new SemaphoreSlim(initialCount: 1);

        var cts = new CancellationTokenSource();
        s.Wait();
        var t = s.WaitAsync(cts.Token);
        s.Release();
        cts.Cancel();


        if (t.Status != TaskStatus.Canceled && s.CurrentCount == 0)
        {
            Console.WriteLine("PASS");
            return 100;
        }
        else
        {
            Console.WriteLine("FAIL");
            Console.WriteLine("Expected task status to not be Canceled and s.CurrentCount == 0");
            Console.WriteLine("Actual: Task: " + t.Status + "; CurrentCount: " + s.CurrentCount);
            return 101;
        }


    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:26,代码来源:test489437.cs

示例5: Main

    public static void Main(){

        CancellationTokenSource cancelTokenSrc = new CancellationTokenSource();
        
        Task<Int32> t = new Task<Int32>( 
            () => { return Sum(100000000, cancelTokenSrc.Token);},
            cancelTokenSrc.Token);       
        
        t.Start();
        
        cancelTokenSrc.Cancel();
        
        Thread.Sleep(1000);
        
        try{
            Console.WriteLine("Waiting...............");
            t.Wait(); 
        }catch(AggregateException ex){        
            ex.Handle(x=> { Console.WriteLine(x.ToString()); return true;});
        } 
        try{
            Console.WriteLine("Extracting Result");
            Console.WriteLine("The Sum is: " + t.Result); // An Int32 value            
        }catch(AggregateException ex){        
            ex.Handle(x=> { Console.WriteLine(x.ToString()); return true;});
        }
    }
开发者ID:ppatoria,项目名称:SoftwareDevelopment,代码行数:27,代码来源:Task.cs

示例6: Main

 public static void Main(String[] args)
 {
     Console.WriteLine("\n-- Cancellation with acknowledgement -------------");
     {
       CancellationTokenSource cts = new CancellationTokenSource();
       CancellationToken token = cts.Token;
       Task task = Task.Run(() => ComputeTaskWithAcknowledgement(token), token);
       Thread.Sleep(0);  // Allow task to be scheduled
       Console.WriteLine(task.Status);   // Running
       cts.Cancel();
       Thread.Sleep(0);
       Console.WriteLine(task.Status);   // Canceled
       try {
     task.Wait();    // Throws AggregateException containing TaskCanceledException
       } catch (Exception exn) {
     Console.WriteLine("Caught " + exn);
       }
       Console.WriteLine(task.Status);   // Canceled
     }
     Console.WriteLine("\n-- Cancellation without acknowledgement ----------");
     {
       CancellationTokenSource cts = new CancellationTokenSource();
       CancellationToken token = cts.Token;
       Task task = Task.Run(() => ComputeTaskWithoutAcknowledgement(token), token);
       Thread.Sleep(0);
       Console.WriteLine(task.Status);   // Running
       cts.Cancel();
       Console.WriteLine(task.Status);   // Running
       task.Wait();
       Console.WriteLine(task.Status);   // RanToCompletion
     }
     Console.WriteLine("\n-- Cancellation before Start ---------------------");
     {
       // Cancel before running
       CancellationTokenSource cts = new CancellationTokenSource();
       CancellationToken token = cts.Token;
       Task task = new Task(delegate { }, token);
       Console.WriteLine(task.Status);   // Created
       cts.Cancel();
       Console.WriteLine(task.Status);   // Canceled
       try {
     task.Start();   // Throws InvalidOperationException
       } catch (Exception exn) {
     Console.WriteLine("Caught " + exn);
       }
       Console.WriteLine(task.Status);   // Canceled
     }
     Console.WriteLine("\n-- Completing before cancellation ----------------");
     {
       CancellationTokenSource cts = new CancellationTokenSource();
       CancellationToken token = cts.Token;
       Task task = new Task(delegate { }, token);
       Console.WriteLine(task.Status);   // Created
       task.Start();
       Thread.Sleep(0);  // Allow task to be scheduled
       Console.WriteLine(task.Status);   // RanToCompletion
       cts.Cancel();
       Console.WriteLine(task.Status);   // RanToCompletion
     }
 }
开发者ID:SimonKITU,项目名称:Fsharp,代码行数:60,代码来源:Example174.cs

示例7: TestCancel

        public void TestCancel()
        {
            using (var waitHandle = new ManualResetEvent(false))
            {
                // Monitor for a cancellation exception
                var task = new WaitTask("Test task", waitHandle);
                bool exceptionThrown = false;
                var cancellationTokenSource = new CancellationTokenSource();
                var waitThread = new Thread(() =>
                {
                    try
                    {
                        task.Run(cancellationTokenSource.Token);
                    }
                    catch (OperationCanceledException)
                    {
                        exceptionThrown = true;
                    }
                });

                // Start and then cancel the download
                waitThread.Start();
                Thread.Sleep(100);
                cancellationTokenSource.Cancel();
                waitThread.Join();

                exceptionThrown.Should().BeTrue(because: task.State.ToString());
            }
        }
开发者ID:nano-byte,项目名称:common,代码行数:29,代码来源:WaitTaskTest.cs

示例8: Main

    static void Main(string[] args)
    {
        var cts = new CancellationTokenSource();
        var ct = cts.Token;

        Task task1 = new Task(() => { Run1(ct); }, ct);

        Task task2 = new Task(Run2);

        try
        {
            task1.Start();
            task2.Start();

            Thread.Sleep(1000);

            cts.Cancel();

            Task.WaitAll(task1, task2);
        }
        catch (AggregateException ex)
        {
            foreach (var e in ex.InnerExceptions)
            {
                Console.WriteLine("\nhi,我是OperationCanceledException:{0}\n", e.Message);
            }

            //task1是否取消
            Console.WriteLine("task1是不是被取消了? {0}", task1.IsCanceled);
            Console.WriteLine("task2是不是被取消了? {0}", task2.IsCanceled);
        }

        Console.Read();
    }
开发者ID:dalinhuang,项目名称:wdeqawes-efrwserd-rgtedrtf,代码行数:34,代码来源:Program.cs

示例9: Precancellation

        public void Precancellation()
        {
            IReadableChannel<int> c = Channel.CreateFromTask(Task.FromResult(42));

            var cts = new CancellationTokenSource();
            cts.Cancel();

            AssertSynchronouslyCanceled(c.WaitToReadAsync(cts.Token), cts.Token);
            AssertSynchronouslyCanceled(c.ReadAsync(cts.Token).AsTask(), cts.Token);
        }
开发者ID:GrimDerp,项目名称:corefxlab,代码行数:10,代码来源:TaskChannelTests.cs

示例10: Cancel_UnpartneredWrite_ThrowsCancellationException

        public async Task Cancel_UnpartneredWrite_ThrowsCancellationException()
        {
            IChannel<int> c = Channel.CreateUnbuffered<int>();
            var cts = new CancellationTokenSource();

            Task w = c.WriteAsync(42, cts.Token);
            Assert.False(w.IsCompleted);

            cts.Cancel();
            await AssertCanceled(w, cts.Token);
        }
开发者ID:Richard-FF,项目名称:corefxlab,代码行数:11,代码来源:UnbufferedChannelTests.cs

示例11: Cancel_UnpartneredRead_ThrowsCancellationException

        public async Task Cancel_UnpartneredRead_ThrowsCancellationException()
        {
            IChannel<int> c = Channel.CreateUnbuffered<int>();
            var cts = new CancellationTokenSource();

            Task r = c.ReadAsync(cts.Token).AsTask();
            Assert.False(r.IsCompleted);

            cts.Cancel();
            await AssertCanceled(r, cts.Token);
        }
开发者ID:Richard-FF,项目名称:corefxlab,代码行数:11,代码来源:UnbufferedChannelTests.cs

示例12: DisposeTestClass

    /// <summary>
    /// Disposes the test class instance. Sends the <see cref="ITestClassDisposeStarting"/> and <see cref="ITestClassDisposeFinished"/>
    /// messages as appropriate.
    /// </summary>
    /// <param name="test">The test</param>
    /// <param name="testClass">The test class instance to be disposed</param>
    /// <param name="messageBus">The message bus used to send the test messages</param>
    /// <param name="timer">The timer used to measure the time taken for construction</param>
    /// <param name="cancellationTokenSource">The cancellation token source</param>
    public static void DisposeTestClass(this ITest test,
                                        object testClass,
                                        IMessageBus messageBus,
                                        ExecutionTimer timer,
                                        CancellationTokenSource cancellationTokenSource)
    {
        var disposable = testClass as IDisposable;
        if (disposable == null)
            return;

        if (!messageBus.QueueMessage(new TestClassDisposeStarting(test)))
            cancellationTokenSource.Cancel();

        try
        {
            timer.Aggregate(disposable.Dispose);
        }
        finally
        {
            if (!messageBus.QueueMessage(new TestClassDisposeFinished(test)))
                cancellationTokenSource.Cancel();
        }
    }
开发者ID:Tofudebeast,项目名称:xunit,代码行数:32,代码来源:ReflectionAbstractionExtensions.cs

示例13: TimeoutAfter

        public static async Task TimeoutAfter(this Task task, int millisecondsTimeout)
        {
            var cts = new CancellationTokenSource();

            if (task == await Task.WhenAny(task, Task.Delay(millisecondsTimeout, cts.Token)))
            {
                cts.Cancel();
                await task;
            }
            else
            {
                throw new TimeoutException();
            }
        }
开发者ID:ChuangYang,项目名称:corefx,代码行数:14,代码来源:TaskTimeoutExtensions.cs

示例14: CancelBeforeWait

        public static void CancelBeforeWait()
        {
            SemaphoreSlim semaphoreSlim = new SemaphoreSlim(2);

            CancellationTokenSource cs = new CancellationTokenSource();
            cs.Cancel();
            CancellationToken ct = cs.Token;

            const int millisec = 100;
            TimeSpan timeSpan = new TimeSpan(100);
            EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(millisec, ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(timeSpan, ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            semaphoreSlim.Dispose();
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:15,代码来源:SemaphoreSlimCancellationTests.cs

示例15: BarrierCancellationTestsCancelAfterWait

        public static void BarrierCancellationTestsCancelAfterWait()
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken cancellationToken = cancellationTokenSource.Token;

            const int numberParticipants = 3;
            Barrier barrier = new Barrier(numberParticipants);

            Task.Run(() => cancellationTokenSource.Cancel());

            //Test that backout occurred.
            Assert.Equal(numberParticipants, barrier.ParticipantsRemaining);

            // the token should not have any listeners.
            // currently we don't expose this.. but it was verified manually
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:16,代码来源:BarrierCancellationTests.cs


注:本文中的CancellationTokenSource.Cancel方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。