简体   繁体   English

是否有太多事件这样的事情?

[英]Is there such a thing as too many events?

public class Human
{
    public void Run(){}
    public void Jump(){}
    public void Eat(){}

    //Generalized approach
    public EventHandler<HumanActivityProgressChanged> ActivityProgressChanged;
    public EventHandler<HumanActivityCompleted> ActivityCompleted;

    //Per-method approach
    public EventHandler<HumanActivityProgressChanged> Running;
    public EventHandler<HumanActivityCompleted> Ran;

    public EventHandler<HumanActivityProgressChanged> Jumping;
    public EventHandler<HumanActivityCompleted> Jumped;

    public EventHandler<HumanActivityProgressChanged> Eating;
    public EventHandler<HumanActivityCompleted> Ate;
}

I have different methods that implements Event-based Async pattern.我有不同的方法来实现基于事件的异步模式。 These methods trigger a ProgressChanged eventargs and a Completed eventargs.这些方法触发ProgressChanged eventargs 和Completed eventargs。 They all trigger the same eventargs (As shown in the code above).它们都触发相同的 eventargs(如上面的代码所示)。

Does it make sense to provide an event per each async method?为每个异步方法提供一个事件是否有意义? Or just provide a generalized event for all async methods?或者只是为所有异步方法提供一个通用事件? Is there such a thing as too much events?是否有太多事件这样的事情?

Both are valid.两者都是有效的。 It really depends on what your intention is.这真的取决于你的意图是什么。

Will you expect a listener to want to listen to all events and repond in similar ways?您是否希望听众想要收听所有事件并以类似的方式进行响应? Go fot the generalized event. Go 为广义事件。

If you are expecting a load of disparate listeners each interested in different aspects, performing wildly different tasks on these events, go for the second.如果您期望有大量不同的听众,每个听众对不同的方面感兴趣,对这些事件执行截然不同的任务,第二个是 go。

The idea behind api design is not to impose a certain way of usage on the clients (Rails users may disagree), but you will give strong hints in the way you design it.. api 设计背后的想法不是将某种使用方式强加给客户端(Rails 用户可能不同意),但您会在设计方式上给出强有力的提示。

The fact that all events have the same EventArgs is an indication that you might replace these events with a single event and pass the activity as a property of the HumanActivityProgressChanged and HumanActivityCompleted types.所有事件都具有相同的 EventArgs 的事实表明您可以将这些事件替换为单个事件并将活动作为 HumanActivityProgressChanged 和 HumanActivityCompleted 类型的属性传递。

There is no law that tells you to do so.没有法律要求您这样做。 It all depends on what you wish to expose and what clients would expect/need.这完全取决于您希望公开什么以及客户期望/需要什么。

It's a question of taste, but I personally prefer the first approach.这是一个品味问题,但我个人更喜欢第一种方法。 For one thing, maintenance is going to be much easier.一方面,维护会容易得多。 And it is simply more efficient to code that way.以这种方式编写代码更有效。

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

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