您的位置:首页 > 其它

线程控制——创建、启动及终止

2012-01-31 14:13 204 查看
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();
}

static void Run()
{
try
{
Console.WriteLine("Run executing.");
Thread.Sleep(5000);
Console.WriteLine("Run completed.");
}
catch (ThreadAbortException ex)
{
Console.WriteLine("Caught thread abort exception.");
}
}
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: