How to pause/suspend a thread then continue it?

浪子不回头ぞ 提交于 2019-11-27 15:31:34
Kiril
ManualResetEvent 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();
}

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();
    }
}
rerun

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!