多线程应用程序中的事件 [英] Events in Multi Threaded Application

查看:79
本文介绍了多线程应用程序中的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在编写一个多线程应用程序,我想要引发事件,如果事件发生在线程1中,它会被通知给其他线程。



例如:在我的应用程序中,我有4个线程(线程A,线程B,线程C,线程D)。在启动应用程序期间启动所有四个线程。线程B和线程C需要知道线程A中是否发生了特定事件。如果发生该事件,线程A如何通知线程B和线程C?



感谢提前。

Hi,

I am writing a multi threaded application and I want raise events such that if event happens in thread 1, it is notified to other threads.

for eg: In my application I have 4 threads (Thread A, Thread B, Thread C, Thread D). All four Threads are started during the start up of the application. Thread B and Thread C need to know if a particular event happens in Thread A. How can Thread A inform Thread B and Thread C if that event occurs?

Thanks in advance.

推荐答案

时间阅读

https://msdn.microsoft.com/en-us/ library / ff649143.aspx [ ^ ]


没有这样的机制。这种机制应该加入框架并不是绝对明显的;我宁愿称之为讨论话题。如果你真的需要它,你必须创建它。事件几乎与线程无关。你只需要学习两者并结合你想要的方式。



但是现在,要小心。许多人会认为这种机制确实存在: Control.Invoke Control.BeginInvoke Dispatcher .Invoke Dispatcher.BeginInvoke System.Collections.Concurrent.BlockingCollection ,任务取消令牌, System.Threading.WaitHandle 和派生类等等。所有这些机制都不是你要问的,但有很多共同之处。它们与所谓的.NET事件无关。此外,您可以将这些机制中的一些与.NET事件结合使用,以实现所需的行为。这是你的技术架构的问题。



你只需要在这里实现基本事实:你不能在任何来自外部的任意线程中调用任何代码的执行。无论你做什么,你都必须在目标线程上实现一些协作行为:它需要运行一些带有消息队列的循环(如UI线程那样,这使得调用成为可能),或类似的东西。我们可以讨论一些方法,但首先你需要进入它并获得更具体的细节。



-SA
There is no such mechanism. It's not absolutely obvious that such mechanism should be added to the framework; I would rather call it a discussable topic. You have to create it if you really need it. Events are pretty much unrelated to threading. You just need to learn both and combine the way you want.

But now, be careful. Many will maintain that such mechanism does exist: Control.Invoke, Control.BeginInvoke, Dispatcher.Invoke, Dispatcher.BeginInvoke, System.Collections.Concurrent.BlockingCollection, task cancellation tokens, System.Threading.WaitHandle and derived classes, and more. All those mechanism are just not what you are asking about, but have a lot in common. They are just not related to what is called ".NET events". Moreover, you can use some of those mechanisms, in combination with .NET events or not, to achieve desired behavior. This is a matter of your technology architecture.

You need to realize only on fundamental fact here: you cannot invoke execution of any code in any arbitrary thread from outside of it. No matter what you do, you have to implement some collaborative behavior on target thread: it needs to run some cycle with message queue (as UI threads do, which makes invocation possible), or something like that. We could discuss some approaches, but first you need to get into it and get to more specific detail.

—SA


这篇关于多线程应用程序中的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆