Replace thread.sleep with something less intense

So I have learnt that my previous solution of having "Thread.Sleep" all over my C# console application (due to waiting web pages to do stuff that I always can't reach with normal WebDriverWaits of Selenium/Chromedriver) is not a good solution, because it freezes the entire thread for the entire duration of the sleep period.

Since I shouldn't do: System.Threading.Thread.Sleep(250); then what should I do? I want it to be a separate statement, not a wrapper for stuff because then this gets really messy really fast. I have dozens of places where I have used Thread.Sleep. But obviously I can use an entire class to do it - if necessary, I just want to be able to call it like a normal method.

So far this is the best I've found working:

class Tools
{
    private static async Task _Sleep(int ms)
    {
        await Task.Delay(ms);
    }

    public static void Sleep(int ms)
    {
        var task = _Sleep(ms);
        task.Wait();
    }
}

Should I replace that one with something else?

Upvotes: 2

Views: 177

Answers (1)

Snufkin
Snufkin

Reputation: 108

There is rarely a really good reason to use any form of Sleep. in 999 cases out of a 1000 it is bad coding. instead of waiting for an arbitrary amount of time you should wait the exact amount of time needed. for example you should use:

await MyFunction();

or callback/event handler functions such as

WebBrowser wb = new WebBrowser();
wb.DocumentCompleted += Wb_DocumentCompleted;
...
private void Wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
 {
   //do your thing...
 }

Upvotes: 3

Related Questions