在Lua中等待异步事件
我有一个 Lua 库,可以为协议创建和解析数据包。当我发送数据包时,我期望从目的地返回回复,然后将其解析到表中。我正在尝试围绕该库编写一个包装器,以便可以进行如下所示的函数调用:result = SendUnicast(dest,packetData)
并将解析后的响应表返回到结果。
我的问题有两个:1)传入消息异步传入,并且在与执行脚本不同的线程上;2)我收到的下一个数据包不一定是我请求的响应,我必须解析传入数据包并匹配序列 ID。
目前的程序流程类似于:
[C# UI Thread]
- Button Click
- Run Lua Script
- 调用 SendUnicast
- 等待回复
[C# 数据线程]
- 传入消息
- 将消息传递给 Lua 解析器函数
- 如果序列与等待命令匹配,则存储已解析的表,恢复阻塞
,存储解析表,恢复阻塞[C# UI Thread]
- Lua scipt 返回解析表
我似乎找不到阻止当前执行脚本的好方法(在UI线程)。创建一个在解析消息时调用的协程,然后 while coroutine.status(co) ~= "dead"
似乎杀死了我的 lua 解释器。
编辑
我将 BMitch 的答案标记为已接受,因为这是处理此问题的正确方法。不过,我要警告您,LuaInterface 不支持协程,我必须自己在 C# 代码中添加对它们的支持。
I have a library in Lua that creates and parses data packets for a protocol. When I send a packet out, I'm expecting a reply back from the destination that is then parsed into a table. I'm trying to write a wrapper around this library so that I can make a function call like the following: result = SendUnicast(dest,packetData)
and have the parsed response table returned to result.
My problem is two fold: 1) The incoming message comes in asynchronously and on a different thread than the executing script and 2) the next packet I receive isn't necessarily the response for my request, I have to parse the incoming packet and match a sequence id.
The program flow currently looks something like:
[C# UI Thread]
- Button Click
- Run Lua Script
- Call SendUnicast
- Wait For Response
[C# Data Thread]
- Incoming Message
- Pass message to Lua parser function
- if sequence matches waiting command, store parsed table, resume blocked
[C# UI Thread]
- Lua scipt returns parsed table
I can't seem to find a good method for blocking the currently executing script (in the UIThread). Creating a coroutine to be called when the message is parsed and then while coroutine.status(co) ~= "dead"
seems to kill my lua interpreter.
EDIT
I'm marking BMitch's answer as accepted because it is the correct way to handle this issue. I will warn you, however, that LuaInterface does not support coroutines and I had to add support for them to the C# code myself.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 UI 线程中,运行:
“等待响应”应类似于:
Lua 中的“传入消息”函数应如下所示:
最后返回到“传入消息”的
C#
,调用适当的 semaphore_post() 函数。抱歉,如果我的
C#
看起来很糟糕,我是 Linux 上的C
程序员,所以我试图保持这一面的通用性。In the UI thread, run:
"Wait for response" should look something like:
The "incoming message" function should look like the following in Lua:
And finally back in
C#
for the "incoming message", call the appropriatesemaphore_post()
function.Sorry if my
C#
looks terrible, I'm aC
programmer on Linux, so I tried to keep that side generic.