【问题标题】:AutoResetEvent Set called after timeoutAutoResetEvent 设置超时后调用
【发布时间】:2012-02-06 18:18:14
【问题描述】:

来自 MSDN “如果没有等待线程,等待句柄将保持信号状态,直到有线程尝试等待它,或者直到它的 Reset 方法被调用。”

EventWaitHandle MyWaitHandle = new AutoResetEvent(false);

线程#1:

public void Method1()
{
  //do something
  //wait for the signal or timeout
  MyWaitHandle.WaitOne(10000);
  //do something else on receiving signal or after timeout
}

线程#2:

//this would be called when there is a response from the external app
public void Method2()
{
  //do something
  //send the signal to waiting thread
  MyWaitHandle.Set();
}

在我的应用程序中,线程 #1 正在向外部应用程序提交请求并等待信号或超时。如果收到来自外部应用程序线程#2 的响应,则设置等待句柄。这个set 即使在超时之后也可以被调用。我的问题是

1) 很有可能在超时后调用Method2 导致设置信号。是不是意味着以后只要有对 Thread #1 的请求,WaitOne(10000) 就没有作用,会立即释放?

2) 在超时的情况下,我是否无论如何不能在Method2 中调用set?这会对 Thread #1 造成任何问题吗?

【问题讨论】:

  • 为什么即使在超时之后也不想设置事件? Method2 是否没有表示 Method1 已经准备好?也许如果您解释一下您要完成的工作...
  • Method2() 不知道它是否在超时后被调用。这就是问题所在。好吧,我可以监控时间并设置一个bool 变量来查看它是否超时。但是我可以根据bool 值调用Set()。如果我不打电话,它会留下任何打开的句柄或任何东西吗?

标签: c# autoresetevent event-wait-handle


【解决方案1】:

为什么不确保等待句柄总是在等待之前重置?

public void Method1()
{
  // Reset the wait handle I'll be using...
  MyWaitHandle.Reset();

  //do something
  //wait for the signal or timeout
  MyWaitHandle.WaitOne(10000);
  //do something else on receiving signal or after timeout
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    • 2013-10-06
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 2021-12-02
    相关资源
    最近更新 更多