We help IT Professionals succeed at work.

C# ASP.Net Threads

Hello Experts,

I have a problem with the Thread.Sleep() method. I have a button event on a popup WebForm that executes a stored procedure and then returns a status message. What I'm attempting to do is close the WebForm a few seconds after the message has displayed.

What I'm actually getting is, the Webform will close as required, but the status message doesn't appear. Removing the Thread.Sleep command and the Response.Write command, does show the status message. Can anyone identify what I'm doing wrong from the code snippet supplied?
Thanks

 
protected void btnCommit_Click(object sender, EventArgs e)
    { 
        try
        {
            // Do Some Work
            lblMessage.Text = "Done";
        }

        // I've removed specific catch blocks

        catch (Exception exp)
        {
            lblMessage.Text = "There was an error, please see log file";
        }

        Thread.Sleep(3000); 
        Response.Write("<script>window.close();</script>");
       
    }

Open in new window

Comment
Watch Question

can you try Resonse.Flush() before the Sleep method?

like the following
protected void btnCommit_Click(object sender, EventArgs e)
    { 
        try
        {
            // Do Some Work
            lblMessage.Text = "Done";
        }

        // I've removed specific catch blocks

        catch (Exception exp)
        {
            lblMessage.Text = "There was an error, please see log file";
        }
        Response.Flush();
        Thread.Sleep(3000); 
        Response.Write("<script>window.close();</script>");
       
    }

Open in new window

Author

Commented:
hi roshmon,

I tried that and I get the same result. I tried removing the Responce.Write and that seems to generate the desired message but only after the Thread.Sleep has been executed. This method then obviously doesn't close the page.
Commented:
Remove the Thread.Sleep and add some javascript that will wait the desired time before closing.

I haven't tested this but something like the following:

Response.Write("<script>setTimeout(window.close(),3000);</script>");