惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园_首页
Vercel News
Vercel News
Last Week in AI
Last Week in AI
罗磊的独立博客
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
IT之家
IT之家
美团技术团队
U
Unit 42
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
J
Java Code Geeks
V
V2EX
量子位
腾讯CDC
S
SegmentFault 最新的问题
The GitHub Blog
The GitHub Blog
G
Google Developers Blog
D
DataBreaches.Net
雷峰网
雷峰网
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 聂微东
L
LangChain Blog
C
Check Point Blog

博客园 - Goodspeed

几种常见的函数 Caesar cipher 遗传算法之背包问题 Transport scheme NOT recognized: [stomp] error running git Canvas 旋转的图片 canvas时钟 火箭起飞 让图标转起来 Tomcat启动脚本 Task中的异常处理 Parallel的陷阱 用Task代替TheadPool 使用ThreadPool代替Thread 线程同步中使用信号量AutoResetEvent 异步和多线程的区别 C#和.NET Framework的关系 为什么泛型不支持协变性? 可空值类型与值类型这间的转换
正确停止线程
Goodspeed · 2014-11-02 · via 博客园 - Goodspeed
using System;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var p = new Program();
            p.Do();
            p.Stop();
        }

        CancellationTokenSource cts = new CancellationTokenSource();

        void Do()
        {
            var worker = new Thread(() =>
            {
                while (true)
                {
                    if (cts.Token.IsCancellationRequested) //检查是否有取消请求
                    {
                        //处理收尾工作
                        Console.WriteLine("this worker was stoped");
                        break;
                    }

                    Console.WriteLine(DateTime.Now);
                    Thread.Sleep(1000);
                }
            });
            worker.Start();
        }

        void Stop()
        {
            Console.ReadKey();
            cts.Cancel(); //发出取消请求
            cts.Token.Register(() => { //进程被停止后通知
                Console.WriteLine("worker has been stoped!");
            });
            Console.ReadKey();
        }
    }
}