views:

164

answers:

3

I have developed windows service to process files whose records will be stored in database. When windows service finds a file it creates a thread and assigns each file to one thread. I have not used Thread Pool. I wanted to know when windows service is stopped, then how to identify how many threads are running and whether they are complete. If all the threads are executed then windows service can be stopped successfully. Otherwis windows service should wait until all threads are executed or aborted. How to implement this.

A: 

You can always store the Thread objects in a list and manage them from there.

Something like:

List<Thread> workerThreads = new Lits<Thread>();
Tread workerThread = new Thread(...);
workerThreads.Add(workerTread);
workerThreads.Start();
Paulo Santos
A: 

You need to keep a list of running threads. You can achieve this by adding each new thread to a list (before calling start), and having the worker method remove the thread from the list (directly, or by raising an event on a controller object).

Basically you need to look after this yourself.

Hope this helps

Binary Worrier
A: 

When windows service is stopped?

When it is closed using SCM, you can check OnStop event to track the closing event

how to identify how many threads are running and whether they are complete? Simply keep every thread you created in an array or list, and to check if the thread still running you can set a boolean variable at the end of the the thread function.

To close the service under specific condition you can use Environment.Exit method.

Ahmed Said
You don't need to add a boolean value. Just check the state of the thread. It already says if the thread is stopped or not.
Paulo Santos
I know you can check ThreadState property, but it causes a lot of problems if you rely on it; check this http://stackoverflow.com/questions/1010030/what-value-is-the-threadstate-property
Ahmed Said