16

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.

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
rvk
  • 737
  • 3
  • 9
  • 23

3 Answers3

31
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();
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Kiril
  • 39,672
  • 31
  • 167
  • 226
  • 2
    Quick note: as written, this example will start in the paused state (as instructed in the `new ManualResetEvent(false);` line). Thanks @Lirik – July.Tech Jan 19 '17 at 23:44
  • i also facing same issue.. Thank you very much @Lirik. your soultion worked for me too. – VARUN NAYAK Jun 09 '17 at 09:20
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();
    }
}
Ian
  • 33,605
  • 26
  • 118
  • 198
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.

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
rerun
  • 25,014
  • 6
  • 48
  • 78