C#阻塞等待回应

2023-09-06 16:57:43 作者:月亮是我掰弯的

我偶然发现了这个问题很多次了,主要是解决其与黑客,而是希望看到一个亲$ P $公关的方式来做到这一点。

I have stumbled upon this problem many times, mostly solved it with hacks, but would like to see a "proprer" way to do it.

我正在写一个通信协议,非常类似于RPC的方式,我的终点问查询,对此他们收到答复。

I'm writing a communication protocol, very similar to RPC in a way that my endpoints ask "queries", to which they receive "replies".

现在......我想实现一个功能,被称为SendCommand,这将发出一个查询,并等待答复这个问题,并将其返回。

Now... I would like to implement a function, called SendCommand, that would send out a query, and wait for the reply to that question, and return it.

所以,我可以做这样的事情

So I could do something like

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

这里的问题是,消息发送和接收异步,而我由一个新的消息,事件,以及它是什么通知。我需要阻塞线程,直到答复中提到查询已经来临,提取其数据内容,并返回给调用者。

The problem with this is that the messages are send and received asynchronously, and I am notified by events that a new message has arrived, and what it was. I would need to block the thread until the reply to the mentioned query has arrived, extract its data content, and return it to the caller.

我的问题是与阻塞线程。阻塞的线程是没有问题的,我们是在谈论一个多线程的应用程序,因此用户界面不会冻结,等等,但问题是什么是实现这一目标的正确方法是什么?

My problem is with blocking the thread. Blocking the thread is not a problem, we are talking about a multi-threaded app, so the UI would not freeze, etc., but the question is what is the correct way to achieve this?

我想沿着初始化SendCommand函数内部信号量,等待它的线的东西,并释放在接收到的消息事件处理程序的信号量(检查后是正确的消息)?

I'm thinking something along the line of initializing a semaphore inside the SendCommand function, waiting for it, and release the semaphore in the message received event handler (after checking it was the correct message)?

问候,   axos88

Regards, axos88

推荐答案

所以,你的问题是关于阻止当前线程并等待答案吗? 我会用一个ManualResetEvent的同步调用者和回调。

So your question is about blocking the current thread and wait for the answer? I would use a ManualResetEvent to synchronise the caller and the callback.

假定用户可以通过一个对象,它接受一个回调方法的发送方法发送您的RPC调用,您可以$ C C你的 SendCommand 这样的方法$:

Supposed you can send your rpc call via a Send method of an object which accepts a callback method, you can code your SendCommand method like this:

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;
}
相关推荐