Thread.Sleep(0)出现问题

时间:2014-03-27 18:28:38

标签: c# .net multithreading

我尝试使用此代码

使用Thread.Sleep(0)测试上下文切换
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadMethod
{
    class Program
    {
        public static void ThreadMethod()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("ThreadProc: {0}", i);

                Thread.Sleep(0);
            }
        }
        static void Main(string[] args)
        {
            Thread t = new Thread(new ThreadStart(ThreadMethod));

            t.Start();

            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Main Thread here!");

                Thread.Sleep(0);
            }



            t.Join();
        }
    }
}

但结果如下:

  

主线程在这里!
  ThreadProc:0
  ThreadProc:1
  ThreadProc:2
  ThreadProc:3
  ThreadProc:4
  ThreadProc:5
  ThreadProc:6
  ThreadProc:7
  ThreadProc:8
  主线程在这里!
  主线程在这里!
  主线程在这里!
  主线程在这里!
  主线程在这里!
  主线程在这里!
  主线程在这里!
  主线程在这里!
  主线程在这里!
  ThreadProc:9

我正在使用Surface PRO 2开发。这种行为是否属于多核系统?

3 个答案:

答案 0 :(得分:0)

如果你想强制进行上下文切换,你应该优先考虑线程/使用Thread.Sleep(1),你也可以在类似的问题上阅读更多相关内容:Thread.Sleep(0) : What is the normal behavior?

答案 1 :(得分:0)

我认为您正在寻找的是Thread.Yield。这将向操作系统发出当前线程不再需要CPU时间的信号,并且如果等待,OS将切换到另一个线程。

答案 2 :(得分:-1)

如果您想要上下文切换,请尝试使用除零以外的其他内容{。}}。

this - 有很好的答案