线程控制——创建、启动及终止
1、创建线程Thread thread = new Thread(new ThreadStart(SortAscending));
2、启动线程
thread.Start();
3、终止线程
如果想要一个进程结束,一种方法是让线程的入口函数执行完毕,但是在很多情况你下这种方式并不足以满足应用程序的需求。
1)Abort
当Abort方法被调用,它会向要终止的线程触发ThreadAbortException,然后线程被终止。示例如下:
class Program
{
static void Main(string[] args)
{
Thread thread = new Thread(Run);
thread.Start();
Thread.Sleep(1000);
thread.Abort();
Console.WriteLine("Aborted.");
Console.ReadLine();
}
static void Run()
{
try
{
Console.WriteLine("Run executing.");
Thread.Sleep(5000);
Console.WriteLine("Run completed.");
}
catch (ThreadAbortException ex)
{
Console.WriteLine("Caught thread abort exception.");
}
}
}
运行结果如图:
2) Join
join方法阻塞调用线程直到指定的线程停止执行。
static void Main(string[] args)
{
Thread thread = new Thread(Run);
thread.Start();
Thread.Sleep(1000);
thread.Join();
Console.WriteLine("Joined.");
Console.ReadLine();
}
www.zzzyk.com
static void Run()
{
try
{
Console.WriteLine("Run executing.");
Thread.Sleep(5000);
Console.WriteLine("Run completed.");
}
catch (ThreadAbortException ex)
{
Console.WriteLine("Caught thread abort exception.");
}
}
}
运行结果:
摘自 Enjoy .NET
补充:软件开发 , C# ,