views:

47

answers:

3

I need to test my vigorously tested code works when called by many threads

So I am calling the code in a loop in a TestMethod using TreadPool.QueueUserWorkItem

however there does not seem to be anyway of holding the current thread while all the threads kicked off are still running.

i.e. pretend code....

using Microsoft.VisualStudio.TestTools.UnitTesting

10 create a server

20 for( a number of iterations ) start a thread running a function

30 while all the threads are still doing stuff hang on to the server

40 now dispose of the server

Without the wait my unit test is disposing of the server before the job is done.

Any insights gratefully received...?

A: 

Is your goal for the main thread to wait for all the other threads to finish before disposing the server?

If so, you should take a look at a very detailed answer I got to a similar question that I asked some time ago. Many different approaches that you should consider are included in the answer.

The answer that was given is located here.

Hope that helps!

Maxim Zaslavsky
yes, just to say thread.Join doesn't work in the test framework - no idea why. Anyhow, I'll have a good read on the link you sent tomorrow (very late here eyes closing and wife snoring) - thanks for the swift reply
Anthony Johnston
From this answer I will be using Join - thanks for the pointer
Anthony Johnston
A: 

I don't know much about .NET, but in java I would do this

10 create a server

20 for( a number of iterations ) start a thread running a function

30 while(all the threads are still doing stuff){
    MainThread.Sleep(xMiliseconds)
}

40 now dispose of the server

That way the MainThread will continually loop, sleep, loop, sleep, until all the threads are done, then it will dispose of the server.

DRJTower
A: 

Join() is the easiest. If you can't do that, you can create an event for each thread and wait for the event to be signled. Alternatively, you could create a semaphore with an initial count for each thread and wait for all threads to release the semaphore.

Mike
join doesn't work in a test, unless your debugging then its fine
Anthony Johnston
Join does work after all, something is throwing an error during the test which doesn't when in debug..
Anthony Johnston