我对ManualResetEvent对象中的方法Set()有一个奇怪的问题。 我创建了一个嵌入DLL COM对象的库,用于与机器通信。
在向COM对象(m_server对象)发送消息之前,我订阅了CommandReceived事件,然后发送消息(SendMessage方法),我等待来自COM对象的响应(WaitOne)。
引发事件后,我使用Set()方法通知ManualResetEvent。有时候,我得到一个例外“Handle is Invalid。”。
显然,ManualResetEvent使用内部句柄。由于某种原因,它会被系统无效。
这是代码:
using (ManualResetEvent msgResponseWait = new ManualResetEvent(false)) {
__RCServer_CommandReceivedEventHandler onCommandReceivedDlg = delegate(ref short isock, string sCommand) {
try {
if (MessageReceived != null) {
MessageReceived(this, null);
}
ServerMessage receivedServerMessage = ServerMessage.Parse(sCommand);
if (msg.Command == receivedServerMessage.Command && msg.GvLocation == receivedServerMessage.GvLocation) {
msg.Value = receivedServerMessage.Value;
msg.ReceivedResponseDateTime = DateTime.Now;
msgResponseWait.Set();
} else {
m_logger.AddTrace(
string.Format("Mismatch between request/response." + Environment.NewLine +
"Command sent: '{0}' / Command received: '{1}'" + Environment.NewLine +
"Location sent: '{2}' / Location received: '{3}'",
msg.Command, receivedServerMessage.Command,
msg.GvLocation, receivedServerMessage.GvLocation),
ELogGroup.Equipment, ESeverityLog.Error);
}
} catch (Exception e) {
m_logger.AddErrHandler(e);
}
};
m_server.CommandReceived += onCommandReceivedDlg;
msg.SendRequestDateTime = DateTime.Now;
m_server.SendMessage(ref iSocket, ref message);
if (!msgResponseWait.WaitOne(msg.TimeoutResponseInMillis)) {
m_logger.AddTrace("No response received", ELogGroup.Equipment, ESeverityLog.Error);
msg.TimeoutOccurred = true;
}
m_server.CommandReceived -= onCommandReceivedDlg;
msg.WaitResponse.Set();
}
感谢您的帮助