zoukankan      html  css  js  c++  java
  • 防止线程退出的几种方案-不再while(true)

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

    方法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 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 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();
         }
    }



  • 相关阅读:
    迭代器、生成器、装饰器(转)
    Python小数据池
    接阿里云oss有感
    VSCode快捷键
    前端跨域调请求 nginx反向代理
    Git生成密钥
    【westorm系列之二】配置格式化
    钉钉安卓端无法渲染数据
    express 写接口
    js正则匹配身份证号 有坑
  • 原文地址:https://www.cnblogs.com/micro-chen/p/6762874.html
Copyright © 2011-2022 走看看