Is it OK to ask handlers of my events return immediately?

陌路散爱 提交于 2019-12-06 00:05:28

Is it OK to ask handlers of my events return immediately?

Yes.

You should explicitly state in your documentation that the library will not work well if the subscribers do not return in a timely fashion.

You should not enforce it

Why? Because you are saying that you are developing a library. A library, as opposed to a framework, leaves the user in control. Hence it's the user decision to do what they want when they subscribe upon your events.

Enforcing handlers to be quick would just increase the complexity making the library harder to use. That's why I think it's better to be clear with the expectations and just refer the users to the documentation if they get problems thanks to their slow handlers.

If it is crucial for your code that the handlers return quickly, you should build it upon a structure that allows you to cancel a handler. As event handlers do not allow you to cancel the execution of a handler, e.g. by a timeout, you have the following options among others:

  • Use event handlers and accept that you do not have any control about what the caller does. Of course you can ask the callers to return within a specific time frame, but you should be prepared that sometimes they will not. You could, however, structure your code so that the event handlers are called at a spot in your code that is not time critical (e.g. in your sample move "Time important stuff" in front of the raise) or use threads to allow for parallel execution.
  • If you do not need the special characteristics of events (e.g. subscription model, subscription of multiple handlers), you can use an alternative approach that allows you to cancel the handler. Depending on the Framework version you use, an alternative might be to use a Task that a caller provides to your class similar to a callback function. Tasks allow you to Wait for a specific number of milliseconds for their completion.

Personally I think it is a bad idea - since Windows is not real-time operation system. In non real-time operation systems you can't count on some method executing 0.5 seconds.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!