问题描述
我需要以不同的优先级异步调用几个方法.
I need to call a couple of methods asynchronously with different priorities.
我的第一个想法是使用ThreadPool并像这样更改Thread的优先级:
My first idea was to use the ThreadPool and change the priority of the Thread like this:
static void Run()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(SomeMethod));
}
static void SomeMethod(object o)
{
Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; // is this ok?
// do some work here
}
这行得通吗?您有什么建议?
Does that work or what do you recommend?
推荐答案
根据 http://msdn.microsoft.com/zh-cn/library/0ka9477y.aspx ,如果您的目标是2.0,它将无法正常工作,它暗示3.5中存在一些差异,但并没有专门针对提及优先级:
According to http://msdn.microsoft.com/en-us/library/0ka9477y.aspx, it won't work if you are targeting 2.0, it alludes to there being some differences in 3.5 but doesn't specifically mention priority:
在几种情况下,创建和管理自己的线程而不是使用线程池线程是合适的:
There are several scenarios in which it is appropriate to create and manage your own threads instead of using thread pool threads:
-
您需要一个前台线程.
You require a foreground thread.
您需要一个具有特定优先级的线程.
You require a thread to have a particular priority.
您有一些任务导致线程长时间阻塞.线程池具有最大数量的线程,因此大量阻塞的线程池线程可能会阻止任务启动.
You have tasks that cause the thread to block for long periods of time. The thread pool has a maximum number of threads, so a large number of blocked thread pool threads might prevent tasks from starting.
您需要将线程放入单线程单元中.所有ThreadPool线程都在多线程单元中.
You need to place threads into a single-threaded apartment. All ThreadPool threads are in the multithreaded apartment.
您需要具有与线程关联的稳定身份,或将线程专用于任务.
You need to have a stable identity associated with the thread, or to dedicate a thread to a task.
您可能需要提出自己的实现,并直接处理线程的创建.
You'll likely need to come up with your own implementation, and handle creation of Threads directly.
问题:您要实现什么目标?您要处理一组任务,并且要先执行高优先级任务,然后再执行优先级较低的任务?还是您实际上想要不同优先级的线程?
Question: What are you trying to achieve do you have a set of tasks to be processed and you want high priority tasks to happen first, and lower ones to happen later; or do you actually want Threads of differing priority?
这篇关于如何以某种优先级调用异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!