Áko*_*dra 2 .net c# events multithreading blocking
我多次偶然发现这个问题,主要是通过 hacks 解决它,但希望看到一种“正确”的方法来做到这一点。
我正在编写一个通信协议,与 RPC 非常相似,我的端点提出“查询”,他们收到“回复”。
现在...我想实现一个名为 SendCommand 的函数,它会发出一个查询,等待对该问题的回复,然后返回它。
所以我可以做类似的事情
int outside_temp = SendCommand(What is the temperature outside).ToInt();
Run Code Online (Sandbox Code Playgroud)
这样做的问题是消息是异步发送和接收的,事件通知我新消息已经到达,以及它是什么。我需要阻塞线程,直到对提到的查询的回复到达,提取其数据内容,并将其返回给调用者。
我的问题是阻塞线程。阻塞线程不是问题,我们谈论的是多线程应用程序,因此 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7529 次 |
| 最近记录: |