酷代码 AI
菜单
服务商

C# 解惑:Monitor.Wait 阻塞线程能否用 AutoResetEvent.Set 恢复执行?附示例!

是的,你可以使用AutoResetEvent类来唤醒一个通过Monitor的Wait方法进入阻塞状态的线程。 当一个线程调用Monitor的Wait方法时,它会释放自己持有的对象锁,然后进入阻塞状态,直到其他线程调用同一对象的NotifyAny或NotifyAll方法,或者另一个线程通过AutoResetEvent的Set方法唤醒它。 当一个线程被唤醒后,它将再次尝试获取对象锁,然后继续执行。通过AutoResetEvent的Set方法可以唤醒处于阻塞状态的线程,并使其恢复执行。 下面是一个简单的示例代码: ```csharp using System; using System.Threading; class Example { static void Main() { AutoResetEvent autoResetEvent = new AutoResetEvent(false); Thread thread = new Thread(() => { // 等待信号 Console.WriteLine("Waiting..."); autoResetEvent.WaitOne(); Console.WriteLine("Continuing..."); }); thread.Start(); // 等待一段时间,以便线程进入阻塞状态 Thread.Sleep(1000); // 发出信号唤醒线程 Console.WriteLine("Setting signal..."); autoResetEvent.Set(); thread.Join(); } } ``` 在这个例子中,一个新线程被创建并开始运行。该线程调用AutoResetEvent的WaitOne方法等待信号。在主线程中,我们等待一段时间以确保新线程已经进入阻塞状态,然后调用AutoResetEvent的Set方法发出信号唤醒新线程。新线程将获取对象锁并继续执行。 ######[AI写代码神器 | 350点数解答 | 2023-11-09 17:54:50]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]