Home > database >  loading screen in c#
loading screen in c#

Time:06-08

I'm trying to use a loading gif image for a loading screen in windows form I want the loading screen to show up for 5 seconds I am trying to implement that with thread.sleep() function but the problem was everything stops in the current winForm includes the gif image itself. I want to delay the 5 seconds of loading time with the animated gif image working

CodePudding user response:

You do not want to use Thread.Sleep due to the problems you are describing. Thread.Sleep is almost never the correct answer in a UI program.

What you want to use is a timer that raises an event after 5s and then stops itself, or use await Task.Delay that wraps a timer internally.

You also need to be careful to ensure that your loading window does not become the main window of your application.

CodePudding user response:

Thread.Sleep() blocks the current thread (ie. the UI thread). You can use this wait method which uses a timer.

public void wait(int milliseconds)
{
    var timer1 = new System.Windows.Forms.Timer();
    if (milliseconds == 0 || milliseconds < 0) return;

    timer1.Interval = milliseconds;
    timer1.Enabled = true;
    timer1.Start();

    timer1.Tick  = (s, e) =>
    {
        timer1.Enabled = false;
        timer1.Stop();
    };

    while (timer1.Enabled)
    {
        Application.DoEvents();
    }
}
  • Related