简体   繁体   English

使用事件处理传递数据

[英]to pass data around using event handling

Anyone can detail the pros and cons to pass data from one class to another using event mechanism? 任何人都可以详细说明使用事件机制将数据从一类传递到另一类的利弊吗? When is the best time to use event to pass data? 什么时候是使用事件传递数据的最佳时间?

Let's take an example. 让我们举个例子。 You have a system where 20 people are subscribed to a weather station for changes in weather. 您有一个系统,其中有20个人订阅了气象站以进行天气变化。 Do you want the weather station to keep track of all the people and services that are subscribed? 您是否希望气象站跟踪所有已订阅的人员和服务?

In my opinion the weather station should not know anything about the people or services that are waiting for weather changes. 在我看来,气象站应该对等待天气变化的人员或服务一无所知。 The weather station should just dispatch an event, and whoever is listening to it will get notified :-) 气象站应该只调度一个事件,任何正在收听的事件都会得到通知:-)

So the point is, you use events to notify observers about an action or state change that occurred in the object. 因此,重点是,您可以使用事件来通知观察者对象中发生的动作或状态更改。 Observers can be difference type of objects since you don't have to know anything about them. 观察者可以是不同类型的对象,因为您不必了解它们。 If someone listens to the object, then he takes care of it. 如果有人听了这个物体,那么他会照顾它。

If it was one to one relation and the object waiting for something to happen is always of the same type, then you wouldn't really need an event for that case. 如果这是一对一的关系,并且等待发生某些事情的对象始终是同一类型,那么对于这种情况,您实际上不需要事件。

Events are also great to decouple systems, like seen in my example above with the weather station. 事件也可以使系统脱钩,就像我在上面的示例中用气象站看到的那样。 The weather station can run on its own without knowing about the services or users that are listening to it. 气象站可以自行运行,而无需了解正在收听的气象站或用户。

Using events will among other things: 使用事件除其他事项外:

  • Decouple the event source from the event receiver 将事件源与事件接收器解耦
  • Allow multiple event receivers to subscribe to the same event 允许多个事件接收者订阅同一事件
  • Provide a well known pattern for implementing eventing 提供一个众所周知的模式来实现事件

One thing to be aware of is how delegates may create unexpected "leaks" in your code: Memory Leak in C# . 要注意的一件事是委托如何在代码中创建意外的“泄漏”: C#中的内存泄漏

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM