如何在类库中订阅应用程序关闭事件

Che*_*riy 3 c# events class-library subscription application-shutdown

某个应用程序使用了一个类库.它包含一个外部使用的A类,以及库中另一个私有类B的静态字段.用户应用程序使用库中的A类实例.

当应用程序关闭时,我想在B类中执行一些清理.是否有可能在没有用户应用程序的任何操作的情况下在B类中捕获应用程序关闭事件?

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

    void Handler()
    {
        // do some work
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 6

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
    }
}
Run Code Online (Sandbox Code Playgroud)