> Is it right to expect that because a timer is running, the thread should
stay alive? or should a thread exit when the function exits despite the
thread still performing work?
Ultimately, a thread starts with a call to a sub/function. When that
sub/function exits/returns, the thread is over. Period. It sounds to me
like this is the source of your problem.
What you need to do in general terms is as follows. According to some rules
of your choosing, you launch worker threads. The rules can include whatever
you want. Maybe you want only a couple running at a time. Maybe some depend
on outputs of others. The specifics of that are up to you. But the app's
main thread should be responsible for launching the workers. A timer for the
main thread is likely to be useful to you.
The worker threads should do their work to completion and then quit. As
they produce output, they should make the data available to the main thread.
Here, thread contention issues need to be solved. What I use is a queue -
threads thread-safely append outputs to a queue. The main thread can
periodically sample the queue (alternatives to polling are also possible).
One thing to worry about is launching too many or not enough threads. Say
you want to retrieve 100 urls from the web. You could launch 100 threads,
each responsible for one url. You could launch one thread responsible for
all 100. Or 10 threads each responsible for 10 urls. 100 threads is bad
because it is resource unfriendly. 1 thread is bad because one slow web
server stops the entire download process, ie it is really single threaded.
10 threads is good because it is not too resource unfriendly and you get all
the benefits of multi-threading.
This is fairly easy to arrange in a standard windows form app which has a
message pump and all that entails. Your main thread is the gui thread, and
it is awakened by events, and you can arrange for your worker threads to do
things that cause the gui thread to respond to an event. So, as time passes
and conditions change, your main thread can launch workers, and as the
workers finish their jobs, the main thread sees and responds to their outputs.
I have no in depth experience with services, console apps, and other
settings, so I don't want to make the same 'fairly easy' assertion. But my
guess is that this same general approach should work in these settings.