暂停线程直到手动恢复

Pea*_*Gen 9 .net c# multithreading visual-studio-2010

如何在c#中手动恢复线程之前,如何将线程置于暂停/休眠状态?

目前我正在中止线程,但这不是我想要的.线程应该睡眠/暂停,直到它触发它唤醒为止.

Ian*_*Ian 18

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

ManualResetEvent mre = new ManualResetEvent();
mre.WaitOne();  // This will wait
Run Code Online (Sandbox Code Playgroud)

在另一个线程上,显然你需要对ManualResetEvent实例的引用.

mre.Set(); // Tells the other thread to go again
Run Code Online (Sandbox Code Playgroud)

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)