Thread.Sleep() without freezing the UI
Asked Answered
M

6

12

First off, I am a beginner in C# and I would like to make this:

class2.method_79(null, RoomItem_0, num, num2, 0, false, true, true);
System.Threading.Thread.Sleep(250);
class2.method_79(null, RoomItem_0, num, num4, 0, false, true, true);
System.Threading.Thread.Sleep(300);
class2.method_79(null, RoomItem_0, num, num6, 0, false, true, true);

But this solution freezes the UI, how could I make the second event occur 250ms after the first etc without freezing the UI?

Mariettemarigold answered 10/6, 2014 at 8:35 Comment(6)
Look up Multithreading.Gondar
Do not block the UI thread. Use a worker thread with a sleep. (Note that you can also better use something like a timer). Please read this https://mcmap.net/q/910378/-why-does-thread-sleep-behave-in-this-way including the link in the answer.Sideling
You could also make the method async and use await Task.Delay(250).Elaterium
possible duplicate of Threading in c#Gondar
Finally I used the async method with await task.delay it works perfectly thanks!!!Mariettemarigold
When everyone Not want top make method async it ist possible to use '''Task.Delay(250).Wait()'''Coenocyte
C
26

The simplest way to use sleep without freezing the UI thread is to make your method asynchronous. To make your method asynchronous add the async modifier.

private void someMethod()

to

private async void someMethod()

Now you can use the await operator to perform asynchronous tasks, in your case.

await Task.Delay(milliseconds);

This makes it an asynchronous method and will run asynchronously from your UI thread.

Note that this is only supported in the Microsoft .NET framework 4.5 and higher.

.

Calipash answered 11/6, 2014 at 7:21 Comment(1)
If awaitable type is not needed by` class2.method_79(null, RoomItem_0, num, num4, 0, false, true, true);` and it is not because await void does not returns anything then the timespan between those method will never be as miliseconds given...Frater
D
3

You could use a Dispatcher Timer to time your execution of methods..

Dubrovnik answered 10/6, 2014 at 8:36 Comment(0)
B
1

Try this code

public static void wait(int milliseconds)
        {
            System.Windows.Forms.Timer 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();
            }
        }
Builtin answered 8/1, 2019 at 4:5 Comment(0)
A
1

Put the function in a Task.Factory.StartNew and, after that, use Thread.Sleep().

Example:

private void btnExample_Click(object sender, EventArgs e)
{
    System.Threading.Tasks.Task.Factory.StartNew(() =>
    {
        System.Threading.Thread.Sleep(2000);
        MessageBox.Show("First message after one second without freezing");
        System.Threading.Thread.Sleep(2000);
        MessageBox.Show("Second message after one second without freezing");
        System.Threading.Thread.Sleep(2000);
        MessageBox.Show("Third message after one second without freezing");
    });
}

Testing video

Axinomancy answered 22/6, 2022 at 19:19 Comment(0)
E
0

You are in the UI thread when you call .Sleep();.

That's why it's freezing the UI. If you need to do this without freezing the UI you would need to run the code in separate threads.

Erminia answered 10/6, 2014 at 8:36 Comment(2)
How could I do to apply it in my code ? I am beginner, and never seen how to use multi-threading before...Mariettemarigold
@Mariettemarigold You will have to learn. Here's a good starting point.Erminia
V
0

Run your time consuming tasks on separate thread. Avoid time consuming tasks and Thread.Sleep() on UI thread.

Versatile answered 10/6, 2014 at 8:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.