像下面这样的代码将启动一个新线程来完成这项工作。有什么方法可以控制该线程的优先级吗?
Task.Factory.StartNew(() => {
// everything here will be executed in a new thread.
// I want to set the priority of this thread to BelowNormal
});
正如其他人提到的,您需要指定一个自定义调度程序来配合您的任务。不幸的是没有合适的内置调度程序。
您可以使用 Glenn 链接到的 ParallelExtensionsExtras,但如果您想要一些可以直接粘贴到代码中的简单内容,请尝试以下操作。像这样使用:
Task.Factory.StartNew(() => {
// everything here will be executed in a thread whose priority is BelowNormal
}, null, TaskCreationOptions.None, PriorityScheduler.BelowNormal);
代码:
public class PriorityScheduler : TaskScheduler
{
public static PriorityScheduler AboveNormal = new PriorityScheduler(ThreadPriority.AboveNormal);
public static PriorityScheduler BelowNormal = new PriorityScheduler(ThreadPriority.BelowNormal);
public static PriorityScheduler Lowest = new PriorityScheduler(ThreadPriority.Lowest);
private BlockingCollection<Task> _tasks = new BlockingCollection<Task>();
private Thread[] _threads;
private ThreadPriority _priority;
private readonly int _maximumConcurrencyLevel = Math.Max(1, Environment.ProcessorCount);
public PriorityScheduler(ThreadPriority priority)
{
_priority = priority;
}
public override int MaximumConcurrencyLevel
{
get { return _maximumConcurrencyLevel; }
}
protected override IEnumerable<Task> GetScheduledTasks()
{
return _tasks;
}
protected override void QueueTask(Task task)
{
_tasks.Add(task);
if (_threads == null)
{
_threads = new Thread[_maximumConcurrencyLevel];
for (int i = 0; i < _threads.Length; i++)
{
int local = i;
_threads[i] = new Thread(() =>
{
foreach (Task t in _tasks.GetConsumingEnumerable())
base.TryExecuteTask(t);
});
_threads[i].Name = $"PriorityScheduler: {i}";
_threads[i].Priority = _priority;
_threads[i].IsBackground = true;
_threads[i].Start();
}
}
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
return false; // we might not want to execute task that should schedule as high or low priority inline
}
}
Notes:
- 工作线程都是后台线程,所以重要的任务不应该使用这个调度器来调度;仅那些在进程关闭时可以丢弃的内容
- 改编自Bnaya Eshet 的实现 https://web.archive.org/web/20150611052413/http://blogs.microsoft.co.il/bnaya/2011/01/29/how-to-schedule-task-on-different-thread-priority/
- 我并不完全理解每一个覆盖;只是同意 Bnaya 的选择
MaximumConcurrencyLevel
, GetScheduledTasks
and TryExecuteTaskInline
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)