• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# CancellationTokenSource类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: 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


示例2: 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


示例3: OutboxCleaner

 public OutboxCleaner(OutboxPersister outboxPersister, TimeSpan timeToKeepDeduplicationData, TimeSpan frequencyToRunCleanup)
 {
     cancellationTokenSource = new CancellationTokenSource();
     this.timeToKeepDeduplicationData = timeToKeepDeduplicationData;
     this.frequencyToRunCleanup = frequencyToRunCleanup;
     this.outboxPersister = outboxPersister;
 }
开发者ID:SimonCropp,项目名称:NsbSqlPersistence,代码行数:7,代码来源:OutboxCleaner.cs


示例4: 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


示例5: 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


示例6: Start

        public void Start(IRequestObject requestObject)
        {
            if (requestObject == null)
                return;

            if (IsBusy)
                return;

            _cancellationTokenSource = new CancellationTokenSource();
            _isBusy = true;

            this._requestObject = requestObject;

            var token = _cancellationTokenSource.Token;
            Task.Run(() =>
            {
                while (!token.IsCancellationRequested)
                {
                    var now = DateTime.Now;
                    if (this._requestObject.CanCreateRequst && now >= NextRequestTme)
                    {
                        NextRequestTme = now.AddSeconds(IntervalSeconds);
                        HandleRequestAsync();
                    }
                    System.Threading.Thread.Sleep(500);
                }

                _isBusy = false;
            }, _cancellationTokenSource.Token);

        }
开发者ID:pantherjain,项目名称:TwseAPIStockMiningTool,代码行数:31,代码来源:RequestScheduler.cs


示例7: Main

    static void Main() {
        
        CancellationTokenSource cts = new CancellationTokenSource();
        CancellationToken token = cts.Token;
        
        Task job = Task.Factory.StartNew(() => {
            for (int i = 0; i < 8; ++i) {
                Console.WriteLine("STEP #{0}", i);
                Thread.Sleep(1000);
                token.ThrowIfCancellationRequested();
            }
            Console.WriteLine("DONE");
        }, token);

        //Thread.Sleep(3500);
        //cts.Cancel();
        cts.CancelAfter(3500);
        Console.WriteLine("(cancellation requested)");

        try {
            job.Wait();
        } catch (Exception) {
            Console.WriteLine("(exception caught)");
        }
        
        Console.WriteLine("FINISHED IN STATE : {0}", job.Status);
    }
开发者ID:Skyish,项目名称:isel-pc-1516-1,代码行数:27,代码来源:Cancel.cs


示例8: 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


示例9: 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


示例10: 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


示例11: FireReconnected

 private static void FireReconnected(IConnection connection,
     CancellationTokenSource reconnectTokenSource,
     ref int reconnectedFired)
 {
     if (!reconnectTokenSource.IsCancellationRequested
         && Interlocked.Exchange(ref reconnectedFired, 1) == 0)
         connection.OnReconnected();
 }
开发者ID:Avatarchik,项目名称:uSignalR,代码行数:8,代码来源:LongPollingTransport.cs


示例12: CancellationToken

 public CancellationToken(bool canceled)
     : this()
 {
     initialized = true;
     canBeCanceled = canceled;
     // This is correctly set later if token originates from a Source
     source = canceled ? CancellationTokenSource.CanceledSource : CancellationTokenSource.NoneSource;
 }
开发者ID:smarkets,项目名称:IronSmarkets,代码行数:8,代码来源:CancellationToken.cs


示例13: FactDiscovererTests

 public FactDiscovererTests()
 {
     aggregator = new ExceptionAggregator();
     cancellationTokenSource = new CancellationTokenSource();
     factAttribute = Mocks.FactAttribute();
     messageBus = new SpyMessageBus();
     options = TestFrameworkOptions.ForDiscovery();
 }
开发者ID:Xarlot,项目名称:xunit,代码行数:8,代码来源:FactDiscovererTests.cs


示例14: 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


示例15: doStuff

        public void doStuff(string exampleString)
        {
            cancelSource = new CancellationTokenSource();
            cancelToken = cancelSource.Token;

            var decRep = new Progress<decimal>((decCount) =>
            {
                if (PctChangedEvent != null) PctChangedEvent(decCount);
            });
            Task.Run(() => { doStuffTask(exampleString, decRep, cancelToken); });
        }
开发者ID:ikdoeict-notes,项目名称:programmeren-3,代码行数:11,代码来源:tasks.cs


示例16: 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


示例17: 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


示例18: CreateRunIntent

    private IRunIntent CreateRunIntent (TaskExecutionNode node)
    {
      var configuration = TaskExecutor.Configuration;

      var runTask = (RunTask) node.RemoteTask;
      var runIntent = RunIntent.Create(configuration.SeparateAppDomain, configuration.ShadowCopy, runTask.VisualStudioProcessId);
      _cancellationTokenSource = runIntent.CancellationTokenSource;

      node.Children.Select(CreateIntent).ForEach(runIntent.AddIntent);

      return runIntent;
    }
开发者ID:igor-toporet,项目名称:TestFx,代码行数:12,代码来源:RecursiveRemoteTaskRunner.cs


示例19: FullDuplexStreamTests

    public FullDuplexStreamTests()
    {
        var tuple = FullDuplexStream.CreateStreams();
        Assert.NotNull(tuple);
        Assert.NotNull(tuple.Item1);
        Assert.NotNull(tuple.Item2);

        this.stream1 = tuple.Item1;
        this.stream2 = tuple.Item2;

        TimeSpan timeout = Debugger.IsAttached ? Timeout.InfiniteTimeSpan : TestTimeout;
        this.testCancellationSource = new CancellationTokenSource(timeout);
    }
开发者ID:AArnott,项目名称:Nerdbank.FullDuplexStream,代码行数:13,代码来源:FullDuplexStreamTests.cs


示例20: Start

 public void Start()
 {
     lock (_taskSyncLocker)
     {
         if (Interlocked.CompareExchange(ref _running, 1, 0) == 0)
         {
             _taskCancellation = new CancellationTokenSource();
             Task task = Task.Factory.StartNew(_taskAction, _taskCancellation.Token,
                 TaskCreationOptions.LongRunning, TaskScheduler.Default).
                 ContinueWith(t => { Interlocked.Exchange(ref _running, 0); });
             Interlocked.Exchange(ref _task, task);
         }
     }
 }
开发者ID:AlonAmsalem,项目名称:ServiceBlocks,代码行数:14,代码来源:TaskWorker.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Candidate类代码示例发布时间:2022-05-24
下一篇:
C# CancellationToken类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap