降低 Task.Factory.StartNew 线程的优先级
像下面这样的代码将启动一个新线程来完成这项工作。有什么方法可以控制该线程的优先级吗?
Task.Factory.StartNew(() => {
// everything here will be executed in a new thread.
// I want to set the priority of this thread to BelowNormal
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如其他人提到的,您需要指定一个自定义调度程序来完成您的任务。不幸的是没有合适的内置调度程序。
您可以使用 Glenn 链接到的 ParallelExtensionsExtras,但如果您想要一些可以直接粘贴到代码中的简单内容,请尝试以下操作。使用方式如下:
代码:
注意:
MaximumConcurrencyLevel
、GetScheduledTasks
和TryExecuteTaskInline
的选择即可。As others have mentioned, you need to specify a custom scheduler to go with your task. Unfortunately there isn't a suitable built-in scheduler.
You could go for the ParallelExtensionsExtras that Glenn linked to, but if you want something simple that can just be pasted right into your code, try the following. Use like this:
The code:
Notes:
MaximumConcurrencyLevel
,GetScheduledTasks
andTryExecuteTaskInline
.任务的线程优先级可以在执行任务的实际方法内设置。但完成后不要忘记恢复优先级,以避免出现问题。
所以首先启动任务:
new TaskFactory().StartNew(StartTaskMethod);
然后设置线程优先级:
更改优先级时,请记住这一点: 为什么*不*更改 ThreadPool(或任务)线程的优先级?
Thread priority for Tasks can be set inside the actual method that executes the Task. But don't forget to restore the priority once you are done to avoid problems.
So first start the Task:
new TaskFactory().StartNew(StartTaskMethod);
Then set the thread priority:
When changing the priority, keep in mind this: Why *not* change the priority of a ThreadPool (or Task) thread?
当您决定是否使用线程池时,这是“不要做”的事情之一;-)
更多详细信息请参见:http://msdn.microsoft.com/en-us/library/0ka9477y.aspx
所以答案是“不,您不能为 Theads 池中创建的线程指定特定优先级
”我打赌您已经了解Thread.Priority< /a> 属性
This is one of "not to do" when you decide whether to use thread pool or not ;-)
More details here: http://msdn.microsoft.com/en-us/library/0ka9477y.aspx
So the answer is "No, you cannot specify particular priority for thread created in Theads Pool"
As of general threadings I bet you already know about Thread.Priority property
要使用
Task
设置优先级,请查看 Microsoft 专家 Stephen Toub 在 这篇 MSDN 博客文章。有关更多详细信息,请不要错过他在第一句话中提到的前两篇文章的链接。对于您的问题,听起来您可能想查看
QueuedTaskScheduler
。For setting priority with
Task
, check out the custom task schedulers described by Microsoft expert Stephen Toub in this MSDN blog post. For further detail, don't miss the links to the previous two posts that he mentions in the first sentence.For your issue, it sounds like you might want to look at the
QueuedTaskScheduler
.