如何等待线程执行 [英] how to wait till thread get executed

查看:86
本文介绍了如何等待线程执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨朋友



我有一个要求。

我正在使用线程来执行一个方法。但我的问题是在某些时候我需要检查线程是否还活着。如果活着我需要等待完成执行。请看内联评论以便更好地理解。

我怎样才能实现这个



谢谢提前



Hi Friends

I have a requirement.
i am using thread to execute a method. but my problem is at some point i need to check whether the thread is alive. if alive i need to wait to complete the execution.Please see the inline comments for better understanding.
How can i achieve this

Thanks in advance

 Thread thread = new Thread(() => DefectFix.GetReqThreadCall(_iTestFactory, TestContext, out ReqXML2, out GetRequestedDataXML));
 thread.Start();

 DefectFix.GetTopPosThreadCall(_iTestFactory, TestContext, ReqXML, out GetTopPositionXML);
//Below line has  to execute only after thread complete its execution. If execution not completed i need to wait till finish
 DefectFix.ServiceValidation(ReqXML, ReqXML2, GetTopPositionXML, GetRequestedDataXML, TestContext.DataRow["TestCaseName"].ToString(), "GetTopPositions", sb);

推荐答案

这是如何:https://msdn.microsoft.com/en-us/library/system.threading.thread.join%28v=vs。 110%29.aspx [ ^ ]。



有很多情况需要等待线程,但是,首先总而言之,如果您使用它,您应该考虑是否真的使用线程。当线程彼此等待时,它可以有效地与只有一个线程相同,从而破坏了线程的目的。请记住,最佳同步不是同步。



-SA


我建​​议你使用 BackgroundWorker [ ^ ]一个线程直接:它包括一个 RunWorkerCompleted Event [ ^ ]会告诉你什么时候完成。



或者,添加一个类级别bool,线程方法设置为true在它退出之前。
I'd suggest that you use a BackgroundWorker[^] instead of a Thread directly: it includes a RunWorkerCompleted Event[^] which would tell you when it is done.

Alternatively, add a class level bool which the thread method sets to true just before it exits.


最简单的方法是使用a WaitHandle:


这篇文章中包含


.NET中线程初学者指南:n的第3部分 [ ^ ]
The easiest way is to use a WaitHandle:

included in this article:
Beginner's Guide to Threading in .NET: Part 3 of n[^]


这篇关于如何等待线程执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆