yoan_gauthier
yoan_gauthier

Reputation: 62

How to delay code without freezing the app

I'm trying to delay my code by 5 seconds this is what I'm using

System.Threading.Thread.Sleep(5000);

However this freeze my app completly I wonder if there's a better way

Upvotes: 0

Views: 515

Answers (1)

Gal Lahat
Gal Lahat

Reputation: 60

There are a lot of ways to achieve that.

One of them is to create a new thread so the main thread will keep going when you freeze the new one.

using System.Threading;
Console.WriteLine("Hello from the main thread");
new Thread(() => 
{
    Thread.CurrentThread.IsBackground = true; 
    Console.WriteLine("Background thread started"); 
    Thread.Sleep(5000);
    Console.WriteLine("Waited 5 sec"); 
}).Start();
Console.WriteLine("The main thread is still running while the other one is waiting");

Upvotes: 1

Related Questions