且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#阻塞等待回应

更新时间:2021-12-11 22:16:32

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