微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

参见英文答案 > How to pause/suspend a thread then continue it?3
在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();
    }
}

原文地址:https://www.jb51.cc/csharp/94941.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐