I would like to change the backgroundcolor of a button for a couple of seconds to lime and then change it back to normal. For some reason it simply doesnt work, I have to wait for those seconds and some things I tested also work but the backgroundcolor isn't changed. This is what I've tried so far:
private void button1_Click(object sender, EventArgs e)
{
button1.BackColor = Color.Lime;
Thread.Sleep(2000);
button1.BackColor = SystemColors.Control;
}
Hopefully someone can help me out with this!
Or you could use a Storyboard if you're working with a XAML technology. I ain't posting implementation details, since they may vary depending on the target technology.
You need a timer. Add a timer control from the toolbox to your form. Double-click on it to add a timer tick event handler
As Horaciux mentioned, you can make use of a Timer object to do this.
Alternatively, you can make use of
await
andTask.Delay
, as mentioned by Jon Skeet in this answer.The problem with
Thread.Sleep
is that it is a blocking operation - in that it will stop anything happening on the thread in question. There are other issues too though - chiefly thatThread.Sleep
doesn't guarantee reactivating the thread in the time specified. When you executeThread.Sleep
, you are basically telling the CPU that your thread doesn't need to be active for the time specified - however, the CPU only guarantees that it won't process it for that time - it doesn't guarantee that it will reactivate at that time, merely at some point after the sleep period (once it has finished processing any other threads currently active).Since you are adding
Thread.Sleep
to your UI thread, you are effectively locking up the entire application for the duration of the sleep.await Task.Delay
on the other hand, won't block the thread, but will return to that line of code in the function once the task in theawait
has completed (in this case, a Delay action). This allows all other methods to continue to operate as normal (button clicks will work fine, etc). This method has the added advantage of keeping all the relevant code in one place, rather than having part of it in a different method.