MSDN documentation indicates that threads started by the TPL will enjoy better scheduling. However, since the threads are based upon ThreadPool, they will be implemented as background threads.
Now, there are some tasks I would like to be carried out in parallel, but it is imperative that these tasks be carried out until completion.
So, how do I create such tasks that are essentially foreground threads, but still enjoy the enhanced scheduling provided by the TPL?
I assume you mean that you want to make sure those tasks complete even if the primary thread is shut down?
I wouldn't suggest depending on the foreground thread staying active if the main thread shuts down. Under normal circumstances, you can keep the main thread active, waiting for the tasks to complete. You can also write a handler that can trap unhandled exceptions and do a graceful shutdown--including waiting for the tasks to complete. If something escapes your unhandled exceptions trap, then your process is probably so corrupt that you shouldn't trust whatever results the tasks deliver.
And, of course, nothing you do will prevent a user from shutting down the threads using Task Manager or something similar.
The TPL does not really give you Threads, it lets you create Tasks. Tasks can be executed on different threads, so Task != Thread.
As with the plain Threadpool, it would not be a good idea to change any Thread-properties.
But you problem could be easily solved by Waiting for any outstanding tasks from the main thread. You usually want to catch and handle their exceptions too.
The
IsBackground
property can be assigned to. I'm not sure if this is "okay" or "not-pants-on-head-dumb" though.Happy coding.
You could write your own
TaskScheduler
implementation. Have a look in the samples for examples of implementing aTaskScheduler
- hopefully it's relatively simple from there.