是否确定要问的处理程序我的事件立即返回?我的、要问、事件、程序

2023-09-04 02:48:30 作者:明眸° Sunshine

我写一个.NET库。其中一个类有事件库的用户需要订阅。是否确定要问的处理程序实现对这些事件快速返回?或者,这是一个普遍问题,对此有一个共同的解决办法吗?

(这将不会是致命的,如果处理了长 - 但事情开始错的,如果他们的处理时间超过半秒左右 - 这是一个网络图书馆和连接会觉得这对同龄人已经下降的事件引发在同一个线程用于发送回复)

例如。

 公共委托无效平();

A级
{
    ///<总结>
    ///如果处理程序未立即返回...我要哭了。
    ///< /总结>
    公共事件娉娉;

    私人无效RaisePing()
    {
         VAR处理器=平;
         如果(处理!= NULL)
             处理程序();
    }

    //这就是所谓的几次谢胜利
    私人无效的主循环()
    {
        如果(东西)
            RaisePing();

        //一次重要的东西 -  musn't多久就来到这里...
    }
}
 

解决方案   

时问处理就OK了我的事件立即返回?

是的。

您应该明确您的文件中指出,该库将无法正常工作,如果用户及时不回来。

您应该不执行呢的

为什么呢?因为你说你正在开发一个图书馆。一个库,而不是一个框架,叶控制的用户。因此,它是用户决定做什么,他们希望,当他们在你的事件订阅。

执法处理程序要快只会增加使得库很难使用的复杂性。这就是为什么我认为最好是明确的预期,只是用户参考文档,如果他们得到,因为其缓慢的处理程序。

海沧区人民政府 海沧台商投资区管委会

I am writing a .NET library. One of the classes has events a user of the library will need to subscribe to. Is it OK to ask implementations of handlers for these events return quickly? Or is this a common problem for which there is a common solution?

(It will no be fatal if the handler took long - but things start to wrong if their handler takes longer than about half a second - it is a networking library and peers connected will think this peer has dropped as the event is raised on the same thread for sending replies)

e.g.

public delegate void Ping();

class A
{
    /// <summary>
    /// If your handler doesn't return quickly... I am going to cry.
    /// </summary>
    public event Ping Ping;

    private void RaisePing() 
    {
         var handler = Ping;
         if(handler != null)
             handler();
    }

    // this is called several times a secound
    private void MainLoop()
    {
        if(something)
            RaisePing();

        // time important stuff - musn't take long to get here...
    }
}

解决方案

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.