C#多线程编程实战1.4终止线程
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
//终止线程
namespace Recipe4
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("starting program...");
Thread t = new Thread(PrintNumbersWithDelay);
t.Start();
Thread.Sleep(TimeSpan.FromSeconds(6));
t.Abort();//给线程注入了ThreadAbortException方法,导致线程被终结。该异常可能在任何时刻发生并可能彻底摧毁应用程序。而且,该技术不一定总是能够终止线程。不推荐此方法终止线程
Console.WriteLine("a thread has been aborted");
Thread t1 = new Thread(PrintNumbers);
t1.Start();
PrintNumbers();
Console.ReadKey();
}
static void PrintNumbersWithDelay()
{
Console.WriteLine("starting...");
for (int i = 1; i < 10; i++)
{
Thread.Sleep(TimeSpan.FromSeconds(2));
Console.WriteLine(i);
}
}
static void PrintNumbers()
{
Console.WriteLine("Starting");
for (int i = 1; i < 10; i++)
{
Console.WriteLine(i);
}
}
}
}