处置问题 [英] Dispose question

查看:110
本文介绍了处置问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些具有了实现IDisposable(定时器,刷子等)私有成员变量的类。我需要尽一切努力确保这些变量是合适的清理由.NET Framework?

I have a number of classes which have private member variables that implement IDisposable (timers, brushes, etc). Do I need to do anything to ensure these variables are cleaned up properly by the .NET Framework?

我遇到指的是有管理的资源与非托管资源的文献。这些术语迷惑我,因为你可以使用非托管资源,实现功能的托管类。这算是一个非托管资源或托管资源?

The literature I've come across is referring to "managed resources" vs. "unmanaged resources". These terms are confusing to me because you can have a managed class which implements functionality using unmanaged resources. Is that considered an "unmanaged resource" or "managed resource" ?

我的理解是,如果你没有一个对象实现IDisposable,那么资源不会被释放,直到退出应用程序上调用Dispose()。对于长时间运行程序时,这种情况可能导致OutOfMemory异常。

My understanding is if you aren't calling Dispose() on an object that implements IDisposable, then the resources aren't being freed until the application exits. This situation could cause OutOfMemory exceptions when running the program for a long period of time.

我怎样才能确保我的code是正确处理资源管理?这对这些对象很重要,因为他们是自定义控件并有可能成为一个抽签消耗IDisposable的资源。我使用C#using语句时,我可以,但有时我需要的对象实施IDisposable的一个成员变量,而使用语句不会帮我在那里。

How can I be sure my code is handling resource management correctly? It's important for these objects because they are custom controls and there may be a lot of drawing which consumes IDisposable resources. I use the C# using statement whenever I can, but sometimes I need to make an object implementing IDisposable a member variable, and the using statement won't help me there.

推荐答案

三个简单的规则。

一个管理的资源是什么,实施的IDisposable 。非托管资源是有点像 HANDLE 如果您通过的P / Invoke了。类如的SafeHandle (或者一个来自的SafeHandle 导出)拥有的非托管资源,但它被认为是一种管理资源本身。因此,拥有非托管资源的任何类本身就是一个管理的资源。

A managed resource is anything implementing IDisposable. An unmanaged resource is something like a HANDLE that you got via p/Invoke. A class like SafeHandle (or one derived from SafeHandle) owns an unmanaged resource, but it is considered a managed resource itself. So any class that owns unmanaged resource is itself a managed resource.

既然你有一个类拥有的管理资源,按照规则2:实施的IDisposable (而不是一个终结)

Since you have a class owning managed resources, follow Rule 2: implement IDisposable (but not a finalizer).

的IDisposable 允许先前清理。如果你不把它的资源的将会的反正清理(他们不会流连,直到进程退出);他们只会在后面清理,并没有关于选择的的他们得到清理。

IDisposable allows for earlier cleanup. If you don't call it, the resources will be cleaned up anyway (they won't hang around until process exit); they'll just be cleaned up later, and you don't have a choice about when they get cleaned up.

这篇关于处置问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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