How to pause/suspend a thread then continue it?

后端 未结 3 1312
北恋
北恋 2020-12-03 21:11

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:

         


        
相关标签:
3条回答
  • 2020-12-03 21:46

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

    0 讨论(0)
  • 2020-12-03 21:49

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-03 21:58
    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();
    
    0 讨论(0)
提交回复
热议问题