本文介绍了更改线程优先级从最低到最高的.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过让一个线程写入到一个链表而另一个线程进程链表,加快东西。

I am trying to speed things by having one thread write to a linked list and another thread process the linked list.

有关某些原因,如果写入到链接列表的方法我使之成为一个任务,而从链表读一个低优先级线程的程序完成作为方法一个整体要快得多。换句话说,我experiense fastests结果做时:

For some reason if the method that writes to the linked list I make it into a task and the method that reads from the linked list a low priority thread the program finishes as a whole much faster. In other words I experiense fastests results when doing:

 Task.Factory.StartNew( AddItems );

 new Thread( startProcessingItems ) { Priority = ThreadPriority.Lowest }.Start();

 while(completed==false)
    Thread.Sleep(0);



也许是因为第一个任务是做这么多的工作比其他线程,这就是为什么一切作为一个整体如果我设置第二个方法的低优先级将更快地完成。

Maybe because the first task is doing so much extra work than the other thread that's why everything as a whole will finish faster if I set the second method a low priority.

反正现在我的问题是 startProcessingItems 与ThreadPriority =最低运行。我怎么会改变它的优先级最高的?如果我创建该方法的新任务将其与低优先级运行?基本上startProcessingItems使用列表结束,一旦有一个名单,我会想先从最高优先级执行。

Anyways now my question is The startProcessingItems runs with ThreadPriority = Lowest. How could I change it's priority to highest? If I create a new Task in that method will it be running with low priority? Basically the startProcessingItems ends with a list and once it has that list I will like to start executing with highest priority.

推荐答案

这是不是一个好办法。首先,的LinkedList< T> 不是线程安全的,所以写它,并在两个线程会引起竞争条件从中读取

This is not a good approach. First off, LinkedList<T> is not thread safe, so writing to it and reading from it in two threads will cause race conditions.

有一个更好的办法是使用。这可以让你无需担心线程安全添加项目(生产线),并阅读项目(消费者线程),因为它是完全线程安全的。

A better approach would be to use BlockingCollection<T>. This allows you to add items (producer thread) and read items (consumer thread) without worrying about thread safety, as it's completely thread safe.

读线程可以直接调用 blockingCollection.GetConsumingEnumerable()的foreach 来得到的元素,写线程只是增加了他们。读线程会的自动阻止的,因此没有必要使用优先一塌糊涂。

The reading thread can just call blockingCollection.GetConsumingEnumerable() in a foreach to get the elements, and the write thread just adds them. The reading thread will automatically block, so there's no need to mess with priorities.

在写入线程是做,你只需要调用 CompleteAdding ,这将反过来,让读线程自动完成。

When the writing thread is "done", you just call CompleteAdding, which will, in turn, allow the reading thread to finish automatically.

这篇关于更改线程优先级从最低到最高的.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:30