据我所知,Thread.Sleep(0)只为具有相同或更高优先级的另一个线程提供时间片。 我做了一些测试应用程序:
class Program
{
public static void ThreadMethod()
{
for (int i = 0; i < 300; i++)
{
Thread.Sleep(0);
Console.WriteLine("{0} ThreadProc: {1}, prio {2} ", Thread.CurrentThread.ManagedThreadId,
i, Thread.CurrentThread.Priority);
}
}
public static void Main()
{
Thread.CurrentThread.Priority = ThreadPriority.Normal;
Thread t = new Thread(new ThreadStart(ThreadMethod));
t.Priority = ThreadPriority.Highest;
Thread t2 = new Thread(new ThreadStart(ThreadMethod));
t2.Priority = ThreadPriority.Lowest;
Process.GetCurrentProcess().ProcessorAffinity = (System.IntPtr)1;
t.Start();
t2.Start();
t2.Join();
t.Join();
}
}
这是模拟单核CPU,据我所知这里应该只执行主要具有最高优先级的线程,但是我看到了: 低prio线程会在每次操作
时不断更改高prio线程互相改变。 (当然在开始和结束时有不同的情况,但最高线程应该总是得到更多的时间片)
答案 0 :(得分:5)
您有2个主题:t
(高优先级)和t2
(低优先级),还有主线程。当高优先级线程执行Thread.Sleep(0)
时 - 它可以给它的时间片的唯一其他线程是t2
,因为即使它具有较低的优先级 - 也没有其他选项。主线程被Join()
阻止,没有代码可以运行,它不需要时间片。
要查看您期望的行为 - 再添加一个具有高优先级的线程:
public static void Main() {
Thread.CurrentThread.Priority = ThreadPriority.Normal;
Thread t = new Thread(new ThreadStart(ThreadMethod));
t.Priority = ThreadPriority.Highest;
Thread t2 = new Thread(new ThreadStart(ThreadMethod));
t2.Priority = ThreadPriority.Lowest;
Thread t3 = new Thread(new ThreadStart(ThreadMethod));
t3.Priority = ThreadPriority.Highest;
Process.GetCurrentProcess().ProcessorAffinity = (System.IntPtr) 1;
t.Start();
t2.Start();
t3.Start();
t3.Join();
t2.Join();
t.Join();
}
然后您将看到高优先级线程彼此分配时间片,因此它们几乎都将独占执行它们的循环,并且只有在它们完成后 - 低优先级线程才会执行其循环。