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
Asked
Active
Viewed 150 times
2
-
Please update your question to include the relevant part of your code. – Wim Ombelets Jun 08 '22 at 12:57
-
2Thread.Sleep() blocks the current thread. You should use a timer or something similar. – string.Empty Jun 08 '22 at 12:59
2 Answers
2
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.

JonasH
- 28,608
- 2
- 10
- 23
1
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();
}
}

string.Empty
- 10,393
- 4
- 39
- 67