Hello everyong im working on a project on my C# class. I have a button that generates 3 random pictures after i click this (Slot Machine) and i need to make it generate those pictures after 3 seconds so it seems like its loading.
Asked
Active
Viewed 81 times
-3
-
5What have you looked up and tried to make it wait? – BugFinder Feb 19 '18 at 16:06
-
C# does not have "click events". What context is your code running in? – Uwe Keim Feb 19 '18 at 16:08
-
At first i checked Thread.Sleep method but many people say it is not good cause it makes the whole programm crash for 3 seconds and you cant do anything else. Then i checked Windows.Forms.Timers but i cant fifure out a way to do the thing i want – Marios P Feb 19 '18 at 16:09
-
Im talking about this one:private void button1_Click – Marios P Feb 19 '18 at 16:09
-
I guess this is Winforms. – Feb 19 '18 at 16:10
-
Use `await Task.Delay`. – SLaks Feb 19 '18 at 16:11
-
Thread.Sleep will hang the UI if you are mistakenly doing all your calculations on it.. – BugFinder Feb 19 '18 at 16:11
3 Answers
1
This won't freeze your UI:
async void button1_Click(object sender, EventArgs e)
{
await Task.Delay(TimeSpan.FromSeconds(3));
do something;
}

Dour High Arch
- 21,513
- 29
- 75
- 90
0
You can pause your current thread using Thread.Sleep
:
using System.Threading;
TimeSpan interval = new TimeSpan(0, 0, 0, 3); // 3 seconds
Thread.Sleep(interval);

Georg Patscheider
- 9,357
- 1
- 26
- 36
-
-
True, doing that on the UI Thread would cause the UI to freeze for 3 seconds. – Georg Patscheider Feb 19 '18 at 16:12
0
I would use the Thread.Sleep() function. Parameter is given in miliseconds ´
private void button1_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(5000);
//following code
}
If you don't want to freeze the UI. You can use this stackoverflow answer