Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pause/suspend a thread then continue it?

I am making an application in C# which uses a winform as the GUI and a separate thread which is running in the background automatically changing things. Ex:

public void Run()
{
    while(true)
    {
        printMessageOnGui("Hey");
        Thread.Sleep(2000);
        // Do more work
    } 
}

How would I make it pause anywhere in the loop, because one iteration of the loop takes around 30 seconds. So I wouldn't want to pause it after its done one loop, I want to pause it on time.

like image 489
rvk Avatar asked Mar 12 '10 06:03

rvk


People also ask

Will pause the thread and allow other threads to restart?

The suspend() method of thread class puts the thread from running to waiting state. This method is used if you want to stop the thread execution and start it again when a certain event occurs. This method allows a thread to temporarily cease execution. The suspended thread can be resumed using the resume() method.

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 do you pause a thread execution?

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.


1 Answers

var mrse = new ManualResetEvent(false);

public void Run() 
{ 
    while (true) 
    { 
        mrse.WaitOne();
        printMessageOnGui("Hey"); 
        Thread.Sleep(2000); . . 
    } 
}

public void Resume() => mrse.Set();
public void Pause() => mrse.Reset();
like image 141
Kiril Avatar answered Sep 17 '22 13:09

Kiril