C# 2008
我已经为此工作了一段时间,但我仍然对在代码中使用 finalize 和 dispose 方法感到困惑。我的问题如下:
我知道在处理非托管资源时我们只需要一个终结器。但是,如果有托管资源调用非托管资源,是否还需要实现终结器?
但是,如果我开发一个不直接或间接使用任何非托管资源的类,我是否应该实现
IDisposable
允许该类的客户端使用“使用语句”?实现 IDisposable 只是为了让你的类的客户使用 using 语句是否可行?
using(myClass objClass = new myClass()) { // Do stuff here }
我在下面开发了这个简单的代码来演示 Finalize/dispose 的使用:
public class NoGateway : IDisposable { private WebClient wc = null; public NoGateway() { wc = new WebClient(); wc.DownloadStringCompleted += wc_DownloadStringCompleted; } // Start the Async call to find if NoGateway is true or false public void NoGatewayStatus() { // Start the Async's download // Do other work here wc.DownloadStringAsync(new Uri(www.xxxx.xxx)); } private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { // Do work here } // Dispose of the NoGateway object public void Dispose() { wc.DownloadStringCompleted -= wc_DownloadStringCompleted; wc.Dispose(); GC.SuppressFinalize(this); } }
关于源代码的问题:
这里我没有添加终结器,通常终结器会被GC调用,终结器会调用Dispose。由于我没有终结器,我什么时候调用 Dispose 方法?是必须调用它的类的客户端吗?
因此,我在示例中的类称为 NoGateway,客户端可以像这样使用和处置该类:
using(NoGateway objNoGateway = new NoGateway()) { // Do stuff here }
执行到 using 块的末尾时会自动调用 Dispose 方法,还是客户端必须手动调用 dispose 方法?IE
NoGateway objNoGateway = new NoGateway(); // Do stuff with object objNoGateway.Dispose(); // finished with it
我在
WebClient
课堂上使用该NoGateway
课程。因为WebClient
实现了IDisposable
接口,这是否意味着WebClient
间接使用了非托管资源?是否有严格的规则来遵循这一点?我怎么知道一个类使用了非托管资源?