从另一个线程唤醒一个线程
我正在使用 .NET (C#)。
如果我有 2 个线程运行 T1 和 T2,T1 是这样的:
while (true)
{
dosomething(); //this is a very fast operation
sleep(5 seconds);
}
同时 T2 正在做一些完全不同的事情,但是时不时地它需要给 T1 一个踢,以便它从睡眠中醒来,即使睡眠时间已经到了没有起来。 我该怎么做呢?
I am using .NET (C#).
if I have 2 threads running T1 and T2 and T1 is like this:
while (true)
{
dosomething(); //this is a very fast operation
sleep(5 seconds);
}
at the same time T2 is doing something completely different however from time to time it needs to give T1 a kick such that it wakes up from the sleep even though the sleep time is not up. How do I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 WaitHandle,例如 ManualResetEvent (或 AutoResetEvent)。
在您的类中,声明一个 ManualResetEvent:
Thread1:
Thread2:
Thread1 将等待 5 秒或直到设置 ManualResetEvent,以先到者为准。
编辑:在上面添加了 AutoResetEvent
Use a WaitHandle, like ManualResetEvent (or AutoResetEvent).
In your class, declare a ManualResetEvent:
Thread1:
Thread2:
Thread1 will wait for 5 seconds or until the ManualResetEvent is Set, whichever comes first.
EDIT: added AutoResetEvent above
如果您想这样做,请不要让线程休眠。 看看这个 所以问题。 另外,此博客进入似乎很有希望。
如果您想在 GOOGLE 上搜索更多相关信息,您可能需要在 .NET 中搜索“线程信号”或类似内容。
If you want to do that, don't put your thread to sleep. Take a look at this SO question. Also, this blog entry seems promising.
If you want to GOOGLE more information on it, you might want to seach for "thread signaling" in .NET or something like that.