Image box not responding to visible true
Hi i am trying out a little experiment with tricking the brain by showing a white circle with a delay for 200 miliseconds after you pushed the button and then after 3 minutes cling the button开发者_JAVA百科 it shows no delay but my image box will not respond to visible=true
public void CircleDelay()
{
Thread.Sleep(200);
imgCircle.Visible = true;
Thread.Sleep(150);
imgCircle.Visible = false;
}
public void CircleNonDelay()
{
imgCircle.Visible = true;
Thread.Sleep(150);
imgCircle.Visible = false;
}
private void button1_Click(object sender, EventArgs e)
{
button1.Text = @"Click!";
if(time == null)
{
time = DateTime.Now.ToString();
}
if (DateTime.Now < Convert.ToDateTime(time).AddMinutes(3))
{
//
CircleDelay();
}
else
{
//
CircleNonDelay();
}
}
Problem is in methods CircleDelay()
and CircleNonDelay()
, UI thread is not getting any time to update the UI and show the image. Once it gets a chance, the code which set the image visibility to false
is already executed that's why you are not seeing the image.
Consider this code
public void CircleNonDelay()
{
//UI thread sets the visibility to true
imgCircle.Visible = true;
//then UI thread sleeps for 150 ms (note the UI thread haven't updated the UI yet because it will do that once it is free from tasks assigned to it)
Thread.Sleep(150);
//UI thread sets visibility to false again
imgCircle.Visible = false;
}
So once the UI thread gets free, you have already set the visibility to false
and same is the problem with other method
What you should do this
public void CircleNonDelay()
{
imgCircle.Visible = true;
// start a background worker or timer which will raise an event after 150 ms
//and call imgCircle.Visible = false; inside that event
}
Windows Forms only draws to the screen then the UI thread is idle - that is when it is not in one of your event handlers. By doing a Thread.Sleep() you don't give the UI a chance to redraw.
If you make a call to Update() you will see the change or call Application.DoEvents() to yield control and let the screen be redrawn.
In effect what you are doing by calling Thread.Sleep() on your UI thread is locking the UI so it won't update or respond to the user. You should to use a Timer to show or hide the picture box so you UI responds().
精彩评论