博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
防止线程退出的几种方案-不再while(true)
阅读量:7070 次
发布时间:2019-06-28

本文共 1016 字,大约阅读时间需要 3 分钟。

有时候 调试程序的时候 。我们需要防止程序退出。比如调试一个定时服务。

 

方法1 while(true) {Thread.Sleep(1000)}

 

方法 2——(推荐) Well when you do that with Thread.Sleep(1000), your processor wastes a tiny amount of time to wake up and do nothing.

You could do something similar with .

When you call WaitOne(), it will wait until it receives a signal.

CancellationTokenSource cancelSource = new CancellationTokenSource(); public override void Run() { //do stuff cancelSource.Token.WaitHandle.WaitOne(); } public override void OnStop() { cancelSource.Cancel(); } 方法3

An alternative approach may be using an AutoResetEvent and instantiate it signaled by default.

public class Program { public static readonly AutoResetEvent ResetEvent = new AutoResetEvent(true); public static void Main(string[] args) { Task.Factory.StartNew ( () => { // Imagine sleep is a long task which ends in 10 seconds Thread.Sleep(10000); // We release the whole AutoResetEvent ResetEvent.Set(); } ); // Once other thread sets the AutoResetEvent, the program ends ResetEvent.WaitOne(); } }
 

转载地址:http://hfhll.baihongyu.com/

你可能感兴趣的文章
剑法三套,程序员也能赚大钱(3) 转
查看>>
Django 信号
查看>>
NLPIR数据语义挖掘技术为企业提供精准管理
查看>>
[Istio]Kubernetes集群部署Istio 1.0
查看>>
HTML5篇
查看>>
分页技术之PageDataSource类
查看>>
How to: Create Instances of ASP.NET User Controls Programmatically
查看>>
关于 python中的 TKinterlistbox 控件加横竖滚动条
查看>>
【leetcode】258. Add Digits
查看>>
xcode错误-第三方的东西他不支持
查看>>
结对项目:黄金点游戏
查看>>
css3之border-image
查看>>
查看静态库(.a文件)内容
查看>>
2013年Linux周刊读者投票出炉 Ubuntu、Android榜上有名
查看>>
任务02——安装 Intellj IDEA,编写一个简易四则运算小程序,并将代码提交到 GitHub...
查看>>
基于nginx的虚拟主机的配置
查看>>
flex布局常用
查看>>
组合逻辑电路
查看>>
站内搜索 简单粗暴放代码
查看>>
第一次作业-四则运算(java基于控制台)
查看>>