我可以从单独的线程在主线程上运行方法吗?

发布于 2024-10-09 19:06:14 字数 250 浏览 0 评论 0原文

我正在从串行端口读取数据,但 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橙味迷妹 2024-10-16 19:06:14

如果主线程是 UI 线程,则可以使用其 SynchronizationContext 或调用 Control.BeginInvoke

If the main thread is a UI thread, you can use its SynchronizationContext or call Control.BeginInvoke.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文