zoukankan      html  css  js  c++  java
  • 线程处理

    案例一、

            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);
                }
            }
    作者:chenze
    出处:https://www.cnblogs.com/chenze-Index/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
    如果文中有什么错误,欢迎指出。以免更多的人被误导。
  • 相关阅读:
    VS自带的诊断工具
    Electron学习
    PC跨*台
    .NET调试学习
    Mac使用
    SSL/TLS
    UKey学习
    授权机制OAuth、JWT
    代理服务器
    .NET相关源码查找
  • 原文地址:https://www.cnblogs.com/chenze-Index/p/15010412.html
Copyright © 2011-2022 走看看