Ave
Ave

Reputation: 4430

Can't click button when using Thread.Sleep in C#?

First, I want to check if my object is null. It will sleep 20 milliseconds in while loop gives user can be interactive with UI.

If the condition in while is correct, I can click the button in UI to break this loop and continues other code.

I tried with by original code:

while (browser.FindElementById("iframe") == null)
{
    if(buttonWasClicked == true)
        return;
    Thread.Sleep(20);
}

I was tried with:

Task.Delay(10000).ContinueWith(x => 
{
    while (browser.FindElementById("iframe") == null)
    {
        if(buttonWasClicked == true)
            return;
    }
});

Seem block code working in the background. So, it skips block code and executes all next line code.

I want it must check before executing next code.

So, I tried with another method. I using Timer but I don't usually use Timer in the application, I don't have any experience with this.

I created new Timer like timer1 and set interval = 20.

At timer1_Tick event, I add code:

private void timer1_Tick(object sender, EventArgs e)
{
    if (browser.FindElementById("iframe") == null)
    {
        if(buttonWasClicked == true)
            break;
    }
    else
        timer1.Stop();
}

And at original code, I replace with:

timer1.Start();

At button_Clicked event, I set to:

timer1.Stop();.

Have any issues with my code?

In debug, it skip event timer1_Tick() and execute all code after line timer.Start().

Upvotes: 0

Views: 320

Answers (1)

seairth
seairth

Reputation: 2062

Assuming your "wait for button push" code is in the GUI thread, this looks like an good use for await. Consider creating an awaitable event (manual or auto) and using that instead of buttonWasClicked. You main code would then look like:

evtButtonClicked = new AsyncManualResetEvent();

await evtButtonClicked.WaitAsync();

// continuation code...

Now, when you call evtButtonClicked.Set(), the continuation code will be queued up to execute on the GUI thread. Recall that the code after await is effectively wrapped into a Task.ContinueWith(), which means that your GUI thread will not block while waiting for the event.

Upvotes: 1

Related Questions