【发布时间】:2011-11-18 10:50:17
【问题描述】:
我有一个线程:
private void start_Click(object sender, EventArgs e) {
//...
Thread th = new Thread(DoWork);
th.Start();
}
知道线程是否终止的最好方法是什么? 我正在寻找如何执行此操作的示例代码。 提前致谢。
【问题讨论】:
标签: c# .net multithreading
我有一个线程:
private void start_Click(object sender, EventArgs e) {
//...
Thread th = new Thread(DoWork);
th.Start();
}
知道线程是否终止的最好方法是什么? 我正在寻找如何执行此操作的示例代码。 提前致谢。
【问题讨论】:
标签: c# .net multithreading
您可以做一些简单的事情。
您可以使用Thread.Join 来查看线程是否已结束。
var thread = new Thread(SomeMethod);
thread.Start();
while (!thread.Join(0)) // nonblocking
{
// Do something else while the thread is still going.
}
当然,如果你不指定超时参数,那么调用线程将阻塞,直到工作线程结束。
您还可以在入口点方法的末尾调用委托或事件。
// This delegate will get executed upon completion of the thread.
Action finished = () => { Console.WriteLine("Finished"); };
var thread = new Thread(
() =>
{
try
{
// Do a bunch of stuff here.
}
finally
{
finished();
}
});
thread.Start();
【讨论】:
this.Invoke(finished);跨度>
如果你只是想等到线程完成,你可以使用。
th.Join();
【讨论】:
只需使用
Thread.join() 正如哈拉姆所说。
检查此链接以获得更清晰的信息:
http://msdn.microsoft.com/en-us/library/95hbf2ta.aspx
使用此方法可确保线程已终止。来电者将 如果线程没有终止,则无限期阻塞。如果线程有 调用 Join 时已经终止,方法返回 马上。
【讨论】: