开发者

How to subscribe to application shutdown event in class library

There is开发者_如何学JAVA a class library used by some application. It contains a class A for external usage with a static field of another private class B inside the library. User application uses instances of class A from the library.

As the application shutdowns I'd like to perform some clean up in class B. Is it possible to catch application shutdown event in class B without any action from user application?

class B
{
    public B()
    {
        // attach Handler() to applicaiton shutdown event
    }

    void Handler()
    {
        // do some work
    }
}


using System.Windows.Forms;

public class B
{
    public B()
    {
        Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
    }

    void Application_ApplicationExit(object sender, EventArgs e)
    {
        //do cleanup of your class
    }
}


If I understand this correctly, your model looks like this:

How to subscribe to application shutdown event in class library

You would then like to have ClassB communicate with Application through ClassA like shown below:

How to subscribe to application shutdown event in class library

From an object-oriented design standpoint, this violates the Law of Demeter, which states that objects should only talk to their direct neighbors. In this regard I would suggest you to do the cleanup in ClassA, if possible.

From an implementation point of view, I would let ClassA explicitly state its dependency on Application by taking an instance of it in the constructor. This way you could easily subscribe to any events published by Application inside ClassA or, potentially, ClassB since inner classes in C# can access the outer class' private members:

public class A
{
    private readonly Application application;

    public A(Application application)
    {
        if (application == null)
        {
            throw new ArgumentNullException("application");
        }

        this.application = application;
        this.application.ApplicationExit += application_ApplicationExit;
    }

    private void application_ApplicationExit(object sender, EventArgs e)
    {
        // Perform cleanup
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜