我有一个线程:如何知道线程执行是否终止?
private void start_Click(object sender, EventArgs e) {
//...
Thread th = new Thread(DoWork);
th.Start();
}
什么知道,如果线程终止的最好方法? 我正在寻找一个示例代码如何做到这一点。 在此先感谢。
我有一个线程:如何知道线程执行是否终止?
private void start_Click(object sender, EventArgs e) {
//...
Thread th = new Thread(DoWork);
th.Start();
}
什么知道,如果线程终止的最好方法? 我正在寻找一个示例代码如何做到这一点。 在此先感谢。
有几件简单的事情你可以做。
您可以使用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();
如果你只是想等到线程完成就可以使用。
th.Join();
只需使用 Thread.join()
作为harlam说。 再检查一下这个链接,更清晰: http://msdn.microsoft.com/en-us/library/95hbf2ta.aspx
使用此方法来确保线程终止。如果线程没有终止,调用者将无限期地阻止 。如果线程在调用Join时已经终止 ,则该方法立即返回 。
通常情况下,回调方法会尽量做到像 一个跨线程操作更新UI指定过程完成。如果你的UI控件不支持交叉线程操作,你会得到一个InvalidOperationException异常,说该控件是从一个线程访问的,而不是它创建的线程,这可以通过调用回调方法来避免,如这个 这个。调用(成品);' –