In some of my integration开发者_高级运维 tests I start multiple threads and wanted to ensure that when the integration test finishes (even if it fails) the thread will be cleaned up. Can anyone recommend an elegant way to do this?
Thanks
EDIT: Thanks for everyone's answers - just to clarify, 'cleaned up' was referring to when the testing threads stops and some of the other threads in a test haven't QTAgent (the testing process) was giving an error.
- Make sure you keep the
Thread
object for every thread you create - Call
Thread.Join()
on all of them at the end of the test, after setting appropriate termination signals. If any thread doesn't terminate quickly enough, this should cause the test to fail even if the test would otherwise have passed.
It's impossible to answer this in more detail without knowing more about your application and test architecture.
If you are using .Net 4.0, and you know how many threads you are going to launch, you could use a CountdownEvent. Then in each thread, have a try/finally block that will set the event. In your cleanup code, wait on the event. You can add a timeout if you like and use that to indicate some error condition.
you can use task in C# 4 and use a cancellation token and/ or handle the end of the thread. see http://msdn.microsoft.com/en-us/library/dd460717.aspx
Using Thread.Join()
will block your current thread until the thread you are calling join on exits. Before joining, you can signal the other threads to exit in a variety of fashions depending on the circumstances.
Calling Thread.Abort()
will raise an abort exception in the target thread which will typically bring it to a stop unless you explicitly do something to prevent that. Although aborts aren't exactly elegant.
Setting Thread.IsBackground
to true on your test threads will make sure they don't keep your process alive when your main threads exit. When the process exits, your background threads will take care of themselves automatically.
Personally, most of my test threads tend to be in the following pattern:
private static readonly ManualResetEvent m_ThreadsShouldExit = new ManualResetEvent(false);
private static void SomeThreadBody()
{
while(!m_ThreadsShouldExit.WaitOne(0))
{
DoSomething();
}
}
精彩评论