How to pause/suspend a thread then continue it?
Asked Answered
J

3

17

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.

Juryman answered 12/3, 2010 at 6:32 Comment(0)
W
32
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();
Whomp answered 12/3, 2010 at 7:2 Comment(2)
Quick note: as written, this example will start in the paused state (as instructed in the new ManualResetEvent(false); line). Thanks @LirikProfessoriate
i also facing same issue.. Thank you very much @Lirik. your soultion worked for me too.Burk
E
5

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 mre

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();
    }
}
Ensoll answered 4/7, 2013 at 15:32 Comment(0)
P
1

You can pause a thread by calling thread.Suspend but that is deprecated. I would take a look at autoresetevent for performing your synchronization.

Patrizius answered 12/3, 2010 at 6:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.