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 there any alternative solutions with the same result that would be safe?
eg.
while(true)
{
doSomework();
i++;
Thread.Sleep(5000);
}
another one is:
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);
}
}
The problems with calling
Thread.Sleepare explained quite succinctly here:The preferred solution: WaitHandles
The most-made-mistake is using
Thread.Sleepwith a while-construct (demo and answer, nice blog-entry)EDIT:
I would like to enhance my answer: