c# - 暂停线程直到手动恢复

标签 c# .net multithreading visual-studio-2010

<分区>

如何将线程置于暂停/ sleep 状态,直到我在 C# 中手动恢复它?

目前我正在中止线程,但这不是我要找的。线程应该休眠/暂停,直到它被触发唤醒。

最佳答案

您应该通过 ManualResetEvent 来执行此操作.

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

在另一个线程上,显然您需要引用 ManualResetEvent 实例。

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

关于c# - 暂停线程直到手动恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17473482/

相关文章:

C# OleDB 删除命令

c# - 通过 c# .net 使用 gmail 帐户登录

c# - 识别对象列表中属性的最小值和最大值

c# - 70-536 考试中的多播委托(delegate)?

c# - ftp 子文件夹下载递归功能不起作用

c# - WCF 4.0 SOA 提交作为事务

c# - 用于 Mono 的 Winforms 或 XWT GUI 设计器?

java - SWT 线程 : GUI not responding even after calling thread. stop()

python - Python 线程中传递的最小参数数量是多少

c++ - 将参数传递给Boost线程函数