为什么之前main()退出调用Dispose()? [英] Why call Dispose() before main() exits?

查看:138
本文介绍了为什么之前main()退出调用Dispose()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的.NET服务,通过在主()循环退出之前finally块调用resourceName.Dispose()清理所有非托管资源。

My .net service cleans up all its unmanaged resources by calling resourceName.Dispose() in a finally block before the Main() loop exits.

难道我真的要这么做?

我在想,因为这个过程已经结束,我不能泄露任何资源是否正确? Windows将关闭不再使用任何手柄,对吧?

Am I correct in thinking that I can’t leak any resources because the process is ending? Windows will close any handles that are no longer being used, right?

推荐答案

有是没有限制的资源类型的可能通过实施的IDisposable 的对象进行封装。绝大多数由 IDisposable接口封装资源对象将操作系统清理,当进程关闭,但有些程序可能使用的资源操作系统一无所知。例如,它要求不受底层数据库支持可能使用一个或多个表来跟踪什么东西是一个锁定模式的数据库应用程序签出,并通过谁。一类签出用这样的表可以确保在一切都被签入,但其的Dispose 法资源,如果该程序关闭,而无需有机会到类清理表,通过该表把守的资源就会留下晃来晃去。由于操作系统就没有什么线索,任何这些表的意思是,它便没有清理它们的方法。

There is no limit to the types of resources that may be encapsulated by an object implementing IDisposable. The vast majority of resources encapsulated by IDisposable objects will be cleaned up by the operating system when a process shuts down, but some programs may use resources the operating system knows nothing about. For example, a database application which requires a locking pattern that isn't supported by the underlying database might use one or more tables to keep track of what things are "checked out" and by whom. A class which "checks out" resources using such tables could ensure in its Dispose method that everything gets checked back in, but if the program shuts down without the class having a chance to clean up the tables, the resources guarded by that table would be left dangling. Since the operating system would have no clue what any of those tables mean, it would have no way of cleaning them up.

这篇关于为什么之前main()退出调用Dispose()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆