如何在两个非 UI 线程中模拟 Control.Invoke()
- 假设有一个线程A,它是一个UI线程。
- 线程 A 创建另一个线程 B,它是非 UI 线程。
- 当线程 B 想要在线程 A 中引发事件时,它所要做的就是 if(Form1.InvokeRequired) Form1.Invoke(相同方法) 并在同一方法中调用事件,对吧?
简单的。但我的问题是,如果 A 和 B 都是非 ui 线程,你想做同样的事情怎么办?没有表单对象可以从线程 B 调用 Invoke()。
如果 WinForms 应用程序这样做,为什么没有像非 UI 线程那样的机制?我错过了什么吗?是否有类似的方法可以从另一个非 ui 线程在一个非 ui 线程中引发事件?
提前致谢。
PS 生产者/消费者模型答案不是我在这里寻找的答案。
- Suppose there's a thread A which is a UI thread.
- Thread A creates another thread B which is a non UI thread.
- When thread B wants to raise an event in thread A all it has to do is
if(Form1.InvokeRequired) Form1.Invoke(same method) and call the event within that same method right?
Simple. But my question is what if you want to do the same thing if both A and B are non-ui threads? Theres no form object to call Invoke() from thread B.
If WinForms apps do it why isn't there a mechanism like that for Non-UI threads? Am I missing something? Is there a similar method to raise an event in one non-ui thread from another non-ui thread?
Thanks in advance.
P.S. The producer/consumer model answers are not the ones I'm looking for here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在第一种情况下,由于线程 B 知道它不是 UI 线程,因此它也可能只调用
.Invoke(...)
。当有两个非 UI 线程时,您将不得不使用某种消息传递/队列。你不能只是中断线程A来运行工作;您必须对线程 A 进行编码以(例如)检查队列中的工作、将项目出列并执行它。这几乎就是 winform 所做的,由 Windows 消息循环提供。如果这不是您正在寻找的答案也没关系 - 它就是这样。
In the first scenario, since thread B knows it isn't the UI thread, it might as well just call
.Invoke(...)
.When there are two non-UI threads, you are going to have to use some kind of message passing / queue. You can't just interrupt thread A to run the work; you must code thread A to (for example) check a queue for work, dequeue an item and execute it. Which is pretty much what winforms does, courtesy of the windows message loop. It doesn't matter if it isn't the answer you're looking for - it is what it is.
如果没有UI,就不存在跨线程的问题。因此只需从线程中调用它们即可。不过,您可能需要一些同步机制。
If there is no UI, there is no issue of cross threading. So simply call them from the thread. You may require some synchronization mechanism though.