Why is Thread.Sleep so harmful

前端 未结 8 2040
天涯浪人
天涯浪人 2020-11-22 06:30

I often see it mentioned that Thread.Sleep(); should not be used, but I can\'t understand why this is so. If Thread.Sleep(); can cause trouble, are

8条回答
  •  别那么骄傲
    2020-11-22 06:53

    For those of you who hasn't seen one valid argument against use of Thread.Sleep in SCENARIO 2, there really is one - application exit be held up by the while loop (SCENARIO 1/3 is just plain stupid so not worthy of more mentioning)

    Many who pretend to be in-the-know, screaming Thread.Sleep is evil failed to mentioned a single valid reason for those of us who demanded a practical reason not to use it - but here it is, thanks to Pete - Thread.Sleep is Evil (can be easily avoided with a timer/handler)

        static void Main(string[] args)
        {
            Thread t = new Thread(new ThreadStart(ThreadFunc));
            t.Start();
    
            Console.WriteLine("Hit any key to exit.");
            Console.ReadLine();
    
            Console.WriteLine("App exiting");
            return;
        }
    
        static void ThreadFunc()
        {
            int i=0;
            try
            {
                while (true)
                {
                    Console.WriteLine(Thread.CurrentThread.ThreadState.ToString() + " " + i);
    
                    Thread.Sleep(1000 * 10);
                    i++;
                }
            }
            finally
            {
                Console.WriteLine("Exiting while loop");
            }
            return;
        }
    

提交回复
热议问题