C#阻塞等待响应

我多次偶然发现这个问题,主要用黑客来解决它,但是希望看到一个“推荐者”的方式去做。

我正在编写一个通信协议,与我的端点询问“查询”的方式非常相似,他们收到“回复”。

现在……我想实现一个名为SendCommand的函数,该函数将发出一个查询,并等待对该问题的回复,并将其返回。

所以我可以做点什么

int outside_temp = SendCommand(What is the temperature outside).ToInt(); 

这样做的问题是消息是异步发送和接收的,并且事件通知我新消息已经到达,以及它是什么。 我需要阻止该线程,直到对所提到的查询的回复到达,提取其数据内容,并将其返回给调用者。

我的问题是阻止线程。 阻止线程不是问题,我们正在谈论一个multithreading应用程序,因此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; } 

你可以做的是,旋转一个调用SendCommand(..)的新线程,然后等待线程hibernate,直到SendCommand发送信号。

例如:

 volatile bool commandCompleted=false; Thread sendCommandThread=new Thread(()=>{ SendCommand(...,()=>{ commandCompleted=true; }) while(!commandCompleted) { Thread.Sleep(100); } });