c# – 为什么Thread.Sleep这么有害

我经常看到它提到Thread.Sleep();不应该使用,但我不明白为什么会这样。如果Thread.Sleep();可能会导致麻烦,有什么替代解决方案具有相同的结果,将是安全的吗?

例如。

while(true)
{
    doSomework();
    i++;
    Thread.Sleep(5000);
}

另一个是:

while (true)
{
    string[] images = Directory.GetFiles(@"C:\Dir", "*.png");

    foreach (string image in images)
    {
        this.Invoke(() => this.Enabled = true);
        pictureBox1.Image = new Bitmap(image);
        Thread.Sleep(1000);
    }
}
调用Thread.Sleep的问题是explained quite succinctly here

Thread.Sleep has its use: simulating lengthy operations while testing/debugging on an MTA thread. In .NET there’s no other reason to use it.

Thread.Sleep(n) means block the current thread for at least the number
of timeslices (or thread quantums) that can occur within n
milliseconds.
The length of a timeslice is different on different versions/types of
Windows and different processors and generally ranges from 15 to 30
milliseconds. This means the thread is almost guaranteed to block for
more than n milliseconds. The likelihood that your thread will
re-awaken exactly after n milliseconds is about as impossible as
impossible can be. So, Thread.Sleep is pointless for timing.

Threads are a limited resource, they take approximately 200,000 cycles
to create and about 100,000 cycles to destroy. By default they
reserve 1 megabyte of virtual memory for its stack and use 2,000-8,000
cycles for each context switch. This makes any waiting thread a
huge waste.

首选解决方案:WaitHandles

最大错误是使用Thread.Sleep与while结构(demo and answernice blog-entry)

编辑:
我想提高我的答案:

We have 2 different use-cases:

  1. We are waiting because we know a
    specific timespan when we should continue (use Thread.Sleep, System.Threading.Timer or alikes)

  2. We are waiting because some condition changes some time …
    keyword(s) is/are some time! if the condition-check is in our code-domain, we
    should use WaitHandles – otherwise the external component should
    provide some kind of hooks … if it doesn’t its design is bad!

My answer mainly covers use-case 2

http://stackoverflow.com/questions/8815895/why-is-thread-sleep-so-harmful

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:c# – 为什么Thread.Sleep这么有害