How do I put a thread into paused/sleep state until I manually resume it in c# ?
Currently I am aborting the thread but this is not what I am looking for. The thread should sleep/pause until it something triggers it to wake up.
Methods Used:sleep(time): This is a method used to sleep the thread for some milliseconds time. suspend(): This is a method used to suspend the thread. The thread will remain suspended and won't perform its tasks until it is resumed. resume(): This is a method used to resume the suspended thread.
Thread. sleep() method can be used to pause the execution of current thread for specified time in milliseconds.
To pause a thread in C#, use the sleep() method.
Java threads allow you to pause for a while, wait for some time and then continue to perform the rest of the task. In the thread class, there's a static method named sleep to do that. You can pass the amount of time you want the current thread to pause it's task for in milliseconds.
You should do this via a ManualResetEvent.
ManualResetEvent mre = new ManualResetEvent();
mre.WaitOne(); // This will wait
On another thread, obviously you'll need a reference to the ManualResetEvent
instance.
mre.Set(); // Tells the other thread to go again
A full example which will print some text, wait for another thread to do something and then resume:
class Program
{
private static ManualResetEvent mre = new ManualResetEvent(false);
static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(SleepAndSet));
t.Start();
Console.WriteLine("Waiting");
mre.WaitOne();
Console.WriteLine("Resuming");
}
public static void SleepAndSet()
{
Thread.Sleep(2000);
mre.Set();
}
}
Look into AutoResetEvent or ManualResetEvent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With