Can threads started by Tasks Parallel Library act

2020-02-06 07:56发布

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?

4条回答
啃猪蹄的小仙女
2楼-- · 2020-02-06 08:32

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.

查看更多
放我归山
3楼-- · 2020-02-06 08:33

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.

查看更多
\"骚年 ilove
4楼-- · 2020-02-06 08:40

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

Happy coding.

查看更多
女痞
5楼-- · 2020-02-06 08:51

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

查看更多
登录 后发表回答