我需要对静态对象调用 Dispose() 吗?

发布于 2024-11-14 01:48:40 字数 59 浏览 5 评论 0原文

如果我有一个静态 WebClient 对象,我是否需要在 Main() 末尾调用 Dispose() ?

If I have a static WebClient object, do I need to call Dispose() on it at the end of Main()?

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

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

发布评论

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

评论(2

相对绾红妆 2024-11-21 01:48:40

当您使用完对象后,无论您将对象放置在何处,都应该始终Dispose() 对象。

如果对象位于静态字段中,则可能更难以确定何时完成它。

You should always Dispose() objects when you're finished with them, regardless of where you put the object.

If the object is in a static field, it may be more difficult to figure out when you're finished with it.

兮颜 2024-11-21 01:48:40

作为一般规则,您应该处理所有一次性物品。这将使他们能够清理任何资源。但是,不能保证在一次性类型上调用 dispose - 使用者可能会忽略调用它,并且 CLR 不会自动调用它。

如果类型确实需要执行其清理逻辑(例如在分配非托管内存或在文件系统上创建文件堆时),它应该结合处置模式实现终结器。如果尚未调用终结器(通常通过处置对象),CLR 将在进程退出时调用终结器。是的,对此有一些警告(例如,错误的终结器可能会破坏其他可终结实例的聚会),但 CLR 保证至少尝试在进程退出时运行所有终结器。

因此从技术上讲,我不认为在这种情况下您绝对必须调用 dispose 方法。然而,无论如何,养成这个习惯是一个好习惯。

As a general rule, you should dispose of any disposable objects. This will allow them to clean up any resources. However, there is no guarantee that dispose will be called on a disposable type - the consumer could neglect to call it, and the CLR does not automatically call it.

If a type really needs its clean-up logic to execute (such as when allocating unmanaged memory or creating a heap of files on the file system), it should implement a finalizer in conjunction with the dispose pattern. The CLR will call the finalizer on process exit if it hasn't already been called (typically through disposing the object). Yes, there are some caveats around this (a bad finalizer can spoil the party for other finalizable instances, for example) but the CLR guarantees to at least try to run all finalizers on process exit.

So technically, I don't there's any reason why you absolutely must call the dispose method in this case. However, it's a good habit to get into nevertheless.

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