今天,要分享的是线程开始运行后指定时间关闭线程
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"));
}
}我们应该把在要调用的方法中设置一个停止变量,用这个变量来作为线程停止的标志,才是相对正确的,下篇给大家介绍如何正确的终止线程!
本文介绍了两种终止线程的方法:一种是直接调用Abort()方法,这种方法可能导致资源未释放;另一种是在线程内部设置停止标记,通过检查该标记来安全地终止线程。推荐使用后者以确保线程能够优雅地退出。

被折叠的 条评论
为什么被折叠?



