Home > Enterprise >  How to change a property for a specified time? C#
How to change a property for a specified time? C#

Time:03-19

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?

CodePudding user response:

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.

  • Related