首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

Thread.Sleep的有关问题

2012-05-21 
Thread.Sleep的问题C# codeclass TimerExampleState{  public int counter 0  public Timer tmr}class

Thread.Sleep的问题

C# code
    class TimerExampleState     {      public int counter = 0;      public Timer tmr;    }    class App     {      public static void Main()      {          TimerExampleState s = new TimerExampleState();          //创建代理对象TimerCallback,该代理将被定时调用          TimerCallback timerDelegate = new TimerCallback(CheckStatus);            //创建一个时间间隔为1s的定时器            Timer timer = new Timer(timerDelegate, s,1000, 1000);            s.tmr = timer;            //主线程停下来等待Timer对象的终止            while(s.tmr != null)            Thread.Sleep(0);            Console.WriteLine("Timer example done.");            Console.ReadLine();      }


while(s.tmr != null)
 Thread.Sleep(0);
这句是什么意思?当启用线程定时器时,主线程就停止等待Timer运行完毕吗?但是为什么是0毫秒,不相当于没有停止线程吗?

[解决办法]
Thread.Sleep(0);
这相当于主动让线程进行切换。
[解决办法]
Thread.Sleep(0); 是将时间片让给比自己优先级高的线程
 Thread.Sleep(1); 是将时间片让给和自己优先级相同或更高的线程

这两句话目的是为了线程的切换,重新让系统进行的时间片分配

热点排行