防止线程退出的几种方案-不再while(true)
2017-04-25 16:38
741 查看
有时候 调试程序的时候 。我们需要防止程序退出。比如调试一个定时服务。方法1 while(true) {Thread.Sleep(1000)}方法 2——(推荐) Well when you do that with
An alternative approach may be using an
Thread.Sleep(1000), your processor wastes a tiny amount of time to wake up and do nothing.You could do something similar with CancelationTokenSource.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
AutoResetEventand 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(); } }
相关文章推荐
- c# 线程启动while(true) 死循环,里边的return导致线程退出情况,查错
- C# 多个线程一直跑着While(true)
- 防止服务器宕机时MySQL数据丢失的几种方案
- 关于解决ASP环境下防止同一用户重复登录的问题的几种方案(20060110原创)
- 防止表单重复提交的几种方案
- Jsp 防止表单重复提交几种方案
- PHP 防止 while true循环 CPU 使用率过高的方法
- 线程退出的几种方式和资源回收【线程编程中避免内存泄漏】
- boost::thread之while(true)型线程终结方法
- 防止服务器宕机时MySQL数据丢失的几种方案
- 正确创建和退出线程,防止内存泄漏
- boost::thread之while(true)型线程终结方法
- 几种方案防止表单重复提交
- 防止服务器宕机时MySQL数据丢失的几种方案
- Jsp 防止表单重复提交几种方案
- boost::thread之while(true)型线程终结方法
- Hibernate使用中防止SQL注入的几种方案
- Jsp 防止表单重复提交几种方案
- 线程退出的几种方法
- java程序中如何为一个while(true)循环计时,超过一定时间比如10个小时就退出循环?