小编Er *_*n G的帖子

为什么Thread.Sleep在运行其他应用程序时等待的时间比请求的长?

关于C#中的线程,我有一个小问题.出于某种原因,当我打开Chrome时,我的线程从32ms延迟加速到16ms延迟,当我关闭Chrome时它会回到32ms.我正在使用Thread.Sleep(1000 / 60)延迟.有人可以解释为什么会发生这种情况,并建议一个可能的解决方案吗?

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading;

 namespace ConsoleApplication2
 {
     class Program
     {
         static bool alive;
         static Thread thread;
         static DateTime last;

         static void Main(string[] args)
         {
             alive = true;
             thread = new Thread(new ThreadStart(Loop));
             thread.Start();

             Console.ReadKey();
         }

         static void Loop()
         {
             last = DateTime.Now;

             while (alive)
             {
                 DateTime current = DateTime.Now;
                 TimeSpan span = current - last;
                 last = current;

                 Console.WriteLine("{0}ms", span.Milliseconds);
                 Thread.Sleep(1000 / 60);
             }
         }
     }
 }
Run Code Online (Sandbox Code Playgroud)

.net c# multithreading behavior

4
推荐指数
2
解决办法
1446
查看次数

标签 统计

.net ×1

behavior ×1

c# ×1

multithreading ×1