pepoluan
pepoluan

Reputation: 6780

Can threads started by Tasks Parallel Library act as foreground threads?

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?

Upvotes: 6

Views: 1817

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1500525

You could write your own TaskScheduler implementation. Have a look in the TaskScheduler documentation for an example of implementing a TaskScheduler - hopefully it's relatively simple from there.

Upvotes: 7

Jim Mischel
Jim Mischel

Reputation: 133995

It is imperative that these tasks be carried out until completion.

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.

Upvotes: 0

user166390
user166390

Reputation:

The IsBackground property can be assigned to. I'm not sure if this is "okay" or "not-pants-on-head-dumb" though.

Happy coding.

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273244

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.

Upvotes: 5

Related Questions