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.
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.
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();
}
}