C#阻塞等待响应

时间:2012-10-17 06:31:46

标签: c# .net multithreading events blocking

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

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

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

所以我可以做类似

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

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

我的问题是阻止线程。阻止线程不是问题,我们讨论的是多线程应用程序,因此用户界面不会冻结等等,但问题是实现此目的的正确方法是什么?

我正在考虑在SendCommand函数中初始化信号量,等待它,并在消息接收事件处理程序中释放信号量(在检查它是正确的消息之后)?

此致   axos88

2 个答案:

答案 0 :(得分:4)

所以你的问题是关于阻止当前线程并等待答案? 我会使用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;
}

答案 1 :(得分:0)

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

例如:

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

 while(!commandCompleted)
{

  Thread.Sleep(100);
}
});
相关问题