Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change a property for a specified time? C#

Hi I am trying to make a "flash animation" where the screen turns white for a fraction of a second, and then goes back to normal.

Here is my code:

private void QuickFallAnimation ()
    {
        plGame.BackColor = Color.White;
        Thread.Sleep(50);
        plGame.BackColor = Color.Black;
    }

The problem is that background-color never changes to white. It just stays black even though the rest of the application pauses for 50 milliseconds. Can anyone help?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The reason for the problem is that your putting your UI thread to sleep. While sleeping the UI is blocked and cannot do a re-render. Never block the UI thread.

changing the code to use async/await should fix the issue:

private async Task QuickFallAnimation ()
    {
        plGame.BackColor = Color.White;
        await Task.Delay(50);
        plGame.BackColor = Color.Black;
    }

You might also need to manually trigger a re-render, something like plGame.Invalidate();

The same could be done with a timer. Task.Delay is simply a wrapper around a timer that is sometimes convenient to use. But for more complex animations, a timer might be more appropriate.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading