我可以从单独的线程在主线程上运行方法吗?
我正在从串行端口读取数据,但 SerialPort 的 DataReceived 事件是在它自己的线程上处理的。我想在主线程上处理这个问题,但简单地声明一个事件并引发它仍然会导致它在 SerialPort 线程上进行处理。我假设我需要声明一个可以调用的委托,但我不知道这是如何工作的。
例如,我想从 DataReceived 线程在主线程上调用 Sub HandleDataReceived(),让 HandleDataReceived() 在主线程上运行。我该怎么做?
I'm reading data from a serial port, but the DataReceived event of SerialPort is handled on it's own thread. I want to handle this on the main thread, but simply declaring an event and raising it still results in it being processed on the SerialPort thread. I'm assuming I need to declare a delegate I can call, but I don't see how that would work.
For example, I want to call Sub HandleDataReceived() on the main thread from the DataReceived thread, having HandleDataReceived() run on the main thread. How would I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果主线程是 UI 线程,则可以使用其
SynchronizationContext
或调用Control.BeginInvoke
。If the main thread is a UI thread, you can use its
SynchronizationContext
or callControl.BeginInvoke
.