我多次偶然发现这个问题,大部分都是通过黑客解决的,但希望看到一种“正确”的方法来做到这一点。
我正在编写一个通信协议(protocol),与 RPC 非常相似,其方式是我的端点询问“查询”,然后接收“回复”。
现在...我想实现一个名为 SendCommand 的函数,它会发送一个查询,等待对该问题的答复,然后返回它。
所以我可以做类似的事情
int outside_temp = SendCommand(What is the temperature outside).ToInt();
这样做的问题是消息是异步发送和接收的,并且我通过事件通知新消息已到达以及它是什么。我需要阻塞线程,直到对上述查询的答复到达,提取其数据内容,并将其返回给调用者。
我的问题是阻塞线程。阻塞线程不是问题,我们谈论的是多线程应用程序,因此 UI 不会卡住等,但问题是实现此目的的正确方法是什么?
我正在考虑在 SendCommand 函数内初始化信号量,等待它,并在消息接收事件处理程序中释放信号量(在检查它是正确的消息后)?
问候, axos88
最佳答案
所以你的问题是阻塞当前线程并等待答案? 我将使用 ManualResetEvent 来同步调用者和回调。
假设您可以通过接受回调方法的对象的 Send 方法发送 rpc 调用,您可以像这样编写 SendCommand
方法:
int SendCommand(int param)
{
ManualResetEvent mre = new ManualResetEvent(false);
// this is the result which will be set in the callback
int result = 0;
// Send an async command with some data and specify a callback method
rpc.SendAsync(data, (returnData) =>
{
// extract / process your return value and
// assign it to an outer scope variable
result = returnData.IntValue;
// signal the blocked thread to continue
mre.Set();
});
// wait for the callback
mre.WaitOne();
return result;
}
关于C# 阻塞等待响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12928435/