C#多线程编程实战(从入门到精通系列)第二篇 指定间隔终止线程

来源:互联网 发布:十月革命 知乎 编辑:程序博客网 时间:2024/04/30 10:58

今天,要分享的是线程开始运行后指定时间关闭线程

static void Main(string[] args){Console.WriteLine("Starting program...");Thread t = new Thread(PrintNumbersWithDelay);t.Start();Thread.Sleep(TimeSpan.FromSeconds(6));t.Abort();Console.WriteLine("A thread has been aborted");}static void PrintNumbersWithDelay(){Console.WriteLine("Starting...");for (int i = 1; i < 10; i++){Thread.Sleep(TimeSpan.FromSeconds(2));Console.WriteLine(i);}}

线程启动后,使用

Thread.Sleep(TimeSpan.FromSeconds(6));
作为指定的间隔时间,然后调用

t.Abort();
终止线程。

其实,终止线程的正确方法应该是这样的:

static void Main(string[] args){RunThreads();}static void RunThreads(){var sample = new ThreadSample();var threadOne = new Thread(sample.CountNumbers);threadOne.Start();Thread.Sleep(TimeSpan.FromSeconds(2));sample.Stop();}class ThreadSample{private bool _isStopped = false;public void Stop(){_isStopped = true;}public void CountNumbers(){long counter = 0;while (!_isStopped){counter++;}Console.WriteLine("线程已终止,counter={0}",counter.ToString("N0"));}}

我们应该把在要调用的方法中设置一个停止变量,用这个变量来作为线程停止的标志,才是相对正确的,下篇给大家介绍如何正确的终止线程!

0 0