码迷,mamicode.com
首页 > 编程语言 > 详细

线程处理

时间:2021-07-14 18:50:15      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:queue   callback   bee   adp   ken   lis   dispose   for   ESS   

案例一、

        public static void Main()
        {
            // Create the token source.
            CancellationTokenSource cts = new CancellationTokenSource();

            // Pass the token to the cancelable operation.
            ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomeWork), cts.Token);
            Thread.Sleep(1000);

            // Request cancellation.
            cts.Cancel();
            Console.WriteLine("Cancellation set in token source...");
            Thread.Sleep(2500);
            // Cancellation should have happened, so call Dispose.
            cts.Dispose();
            Console.ReadLine();
        }

        // Thread 2: The listener
        static void DoSomeWork(object obj)
        {
            CancellationToken token = (CancellationToken)obj;

            for (int i = 0; i < 100000; i++)
            {
                if (token.IsCancellationRequested)
                {
                    Console.WriteLine("In iteration {0}, cancellation has been requested...",
                                      i + 1);
                    // Perform cleanup if necessary.
                    //...
                    // Terminate the operation.
                    break;
                }
                // Simulate some work.
                //Thread.SpinWait(500000);
                Console.WriteLine("{0}...", i + 1);
            }
        }

 

线程处理

标签:queue   callback   bee   adp   ken   lis   dispose   for   ESS   

原文地址:https://www.cnblogs.com/chenze-Index/p/15010412.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!