Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pausing a thread until manually resumed [duplicate]

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.

like image 475
PeakGen Avatar asked Jul 04 '13 15:07

PeakGen


People also ask

How do you pause a resume and thread?

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.

How can we pause the execution of a thread for specific time?

Thread. sleep() method can be used to pause the execution of current thread for specified time in milliseconds.

Can you pause a thread in C#?

To pause a thread in C#, use the sleep() method.

Can we pause a thread in Java?

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.


2 Answers

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();
    }
}
like image 61
Ian Avatar answered Oct 20 '22 00:10

Ian


Look into AutoResetEvent or ManualResetEvent.

like image 31
spender Avatar answered Oct 19 '22 23:10

spender