防止線程退出的幾種方案-不再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(); } }




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM