【问题标题】:How to pause/suspend a thread then continue it?如何暂停/暂停线程然后继续它?
【发布时间】:2020-11-27 13:30:25
【问题描述】:

我正在用 C# 制作一个应用程序,它使用 winform 作为 GUI 和一个在后台运行的单独线程,自动改变事物。例如:

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

如何让它在循环中的任何地方暂停,因为循环的一次迭代大约需要 30 秒。所以我不想在它完成一个循环后暂停它,我想按时暂停它。

【问题讨论】:

    标签: c# multithreading suspend


    【解决方案1】:
    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();
    

    【讨论】:

    • 快速说明:如所写,此示例将以暂停状态开始(如new ManualResetEvent(false); 行中的说明)。谢谢@Lirik
    • 我也面临同样的问题。非常感谢@Lirik。你的灵魂也对我有用。
    【解决方案2】:

    您应该通过ManualResetEvent 进行此操作。

    ManualResetEvent mre = new ManualResetEvent();
    mre.WaitOne();  // This will wait
    

    在另一个线程上,显然您需要对 mre 的引用

    mre.Set(); // Tells the other thread to go again
    

    一个完整的例子,它将打印一些文本,等待另一个线程做某事然后恢复:

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

    【讨论】:

      【解决方案3】:

      您可以通过调用 thread.Suspend 来暂停线程,但这已被弃用。我会看看 autoresetevent 以执行您的同步。

      【讨论】:

        猜你喜欢
        • 2012-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-14
        • 1970-01-01
        • 2016-04-25
        • 1970-01-01
        相关资源
        最近更新 更多