从另一个线程唤醒一个线程

发布于 2024-07-24 19:43:18 字数 257 浏览 6 评论 0原文

我正在使用 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冰之心 2024-07-31 19:43:19

使用 WaitHandle,例如 ManualResetEvent (或 AutoResetEvent)。

在您的类中,声明一个 ManualResetEvent:

private ManualResetEvent myEvent = new ManualResetEvent(false);

Thread1:

while(true) {
    doSomething();
    myEvent.WaitOne(5000);
    myEvent.Reset();
}

Thread2:

myEvent.Set();

Thread1 将等待 5 秒或直到设置 ManualResetEvent,以先到者为准。

编辑:在上面添加了 AutoResetEvent

Use a WaitHandle, like ManualResetEvent (or AutoResetEvent).

In your class, declare a ManualResetEvent:

private ManualResetEvent myEvent = new ManualResetEvent(false);

Thread1:

while(true) {
    doSomething();
    myEvent.WaitOne(5000);
    myEvent.Reset();
}

Thread2:

myEvent.Set();

Thread1 will wait for 5 seconds or until the ManualResetEvent is Set, whichever comes first.

EDIT: added AutoResetEvent above

忆依然 2024-07-31 19:43:19

如果您想这样做,请不要让线程休眠。 看看这个 所以问题。 另外,此博客进入似乎很有希望。

如果您想在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文