9

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.

Ian
  • 33,605
  • 26
  • 118
  • 198
PeakGen
  • 21,894
  • 86
  • 261
  • 463
  • 1
    I've never done this before but I am thinking along the lines of blocking the thread using a ManualResetEvent. – User 12345678 Jul 04 '13 at 15:05
  • @ByteBlast: It does look like a duplicate, however the answer on the other question isn't particularly great :/ – Ian Jul 04 '13 at 15:32
  • Make sure to do this only to a background thread. A UI thread (any thread that has joined a COM STA, usually the main thread, and generally any thread that owns a window for any reason) *must* continue to run and pump messages or it will cause stability problems. – Euro Micelli Jul 04 '13 at 21:48

2 Answers2

18

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();
    }
}
Ian
  • 33,605
  • 26
  • 118
  • 198
4

Look into AutoResetEvent or ManualResetEvent.

spender
  • 117,338
  • 33
  • 229
  • 351