像下面这样的代码将启动一个新线程来执行任务。是否有办法控制该线程的优先级?
Task.Factory.StartNew(() => {
// everything here will be executed in a new thread.
// I want to set the priority of this thread to BelowNormal
});
像下面这样的代码将启动一个新线程来执行任务。是否有办法控制该线程的优先级?
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
}
}
注意事项:
MaximumConcurrencyLevel
、GetScheduledTasks
和TryExecuteTaskInline
。在执行Task的实际方法中,可以设置Tasks的线程优先级。但不要忘记在完成后恢复优先级,以避免出现问题。
因此,首先启动Task:
new TaskFactory().StartNew(StartTaskMethod);
然后设置线程优先级:
void StartTaskMethod()
{
try
{
// Change the thread priority to the one required.
Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;
// Execute the task logic.
DoSomething();
}
finally
{
// Restore the thread default priority.
Thread.CurrentThread.Priority = ThreadPriority.Normal;
}
}
调整优先级的时候要记住这一点:为什么不改变ThreadPool(或Task)线程的优先级?
在决定是否使用线程池时,这是"不要做"的之一 ;-)
更多详情请参见:http://msdn.microsoft.com/en-us/library/0ka9477y.aspx
因此,答案是“不能为在线程池中创建的线程指定特定优先级”。
至于一般线程,我打赌您已经知道Thread.Priority属性了。
Task
设置优先级,请查阅由微软专家Stephen Toub在此 MSDN 博客文章中介绍的自定义任务调度程序。如需进一步了解,请勿错过他在第一句中提到的前两篇文章链接。QueuedTaskScheduler
。
BlockingCollection<T>
处理,这里没有花哨的多线程。你确定是这段代码死锁了,而不是你的任务? - Roman Starkov