Application.ThreadException:如果不分离,内存泄漏?

发布于 2024-12-10 12:12:26 字数 373 浏览 0 评论 0原文

Application.ThreadException 的参考页

因为这是一个静态事件,所以您必须分离事件处理程序 当您的应用程序被处置时,否则会导致内存泄漏。

尽管该页面上的示例代码没有分离事件处理程序,但如果事件处理程序没有分离,它真的会泄漏吗?

似乎唯一应该分离处理程序的时间是应用程序关闭时。在这种情况下,无论处理程序是否分离,应用程序使用的所有内存都会被释放?

The reference page for Application.ThreadException says

Because this is a static event, you must detach your event handlers
when your application is disposed, or memory leaks will result.

Notwithstanding the fact that the sample code on that very page does not detach the event handler, does it really leak if the event handler is not detached?

It seems the only time the handler should be detached is if the application shuts down. In that case, whether or not the handler is detached, all the memory used by the application will be freed anyway?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

穿透光 2024-12-17 12:12:26

这可能非常不常见,但由于某种原因,WinForms 应用程序的 Main() 方法可能如下所示:

static bool AbortStartup { get; set; }

[STAThread]
public static void Main()
{
    Application.Run(new CancelableSplashScreen());

    if (!AbortStartup)
        Application.Run(new MainWindow());
}

当启动屏幕关闭时,主窗口将出现,除非启动屏幕设置了AbortStatup 属性设置为 true。如果您从初始屏幕内向 Application.ThreadException 添加了一个事件处理程序,则 CancelableSplashScreen 的实例将不会被垃圾回收,直到应用程序终止,这可能是相当大的。时间稍后。

It is probably very uncommon, but a WinForms application's Main() method could possibly, for some reason, look like this:

static bool AbortStartup { get; set; }

[STAThread]
public static void Main()
{
    Application.Run(new CancelableSplashScreen());

    if (!AbortStartup)
        Application.Run(new MainWindow());
}

When the splash screen closes, the main window will appear, unless the splash screen set the AbortStatup property to true. If you added an event handler to Application.ThreadException from within the splash screen, the instance of CancelableSplashScreen won't be garbage collected until the application terminates, which may be a considerable time later.

哑剧 2024-12-17 12:12:26

如果您放弃对对象的引用(假设它是一个实例方法,即事件处理程序),那么是的,将会出现泄漏;您将无法取消订阅该事件(因为您不再拥有该实例),并且该对象将一直存在,直到应用程序域结束(因为这是静态变量的生命周期)。

If you let the reference to the object go (assuming it's an instance method that is the event handler) then yes, there will be a leak; you won't be able to unsubscribe from the event (since you don't have the instance anymore) and the object will exist until the app domain ends (as that is the lifetime of static variables).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文