考虑以下代码:
namespace DisposeTest
{
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Calling Test");
Test();
Console.WriteLine("Call to Test done");
}
static void Test()
{
DisposeImplementation di = new DisposeImplementation();
}
}
internal class DisposeImplementation : IDisposable
{
~DisposeImplementation()
{
Console.WriteLine("~ in DisposeImplementation instance called");
}
public void Dispose()
{
Console.WriteLine("Dispose in DisposeImplementation instance called");
}
}
}
Dispose 永远不会被调用,即使我在 Test();
调用之后放置了一个等待循环.所以这很糟糕.我想编写一个简单易用的类,以确保清理所有可能的资源.我不想把这个责任推给我班级的用户.
The Dispose just never get's called, even if I put a wait loop after the Test();
invocation. So that quite sucks. I want to write a class that is straightforward and very easy to use, to make sure that every possible resource is cleaned up. I don't want to put that responsibilty to the user of my class.
可能的解决方案:使用using
,或者自己调用Dispose(基本一样).我可以强制用户使用 using 吗?或者我可以强制调用 dispose 吗?
Possible solution: use using
, or call Dispose myself(basicly the same). Can I force the user to use a using? Or can I force the dispose to be called?
在 Test();
之后调用 GC.Collect();
也不起作用.
Calling GC.Collect();
after Test();
doesn't work either.
将 di
置于 null
也不会调用 Dispose.Deconstructor 确实有效,因此对象在退出 Test()
Putting di
to null
doesn't invoke Dispose either. The Deconstructor DOES work, so the object get's deconstructed when it exits Test()
好的,伙计们,现在很清楚了!
Ok guys, it's clear now!
谢谢大家的回答!我将在评论中添加警告!
Thank you all for your answers! I will add a warning in the comment!
我想写一个类简单易用,确保一切可能资源被清理.我不想把责任交给用户我班的.
I want to write a class that is straightforward and very easy to use, to make sure that every possible resource is cleaned up. I don't want to put that responsibilty to the user of my class.
你不能那样做.内存管理根本不是为了容纳非专门的内存资源而构建的.
You can't do that. The memory management is simply not built to accomodate resources that are not memory specifically.
IDisposable 模式旨在为开发人员提供一种在对象完成时告知对象的方式,而不是让内存管理尝试通过使用引用计数之类的东西来解决这个问题.
The IDisposable pattern is intended for developers as a way of telling an object when they are done with it, instead of having the memory management trying to figure that out by using things like reference counting.
对于未能正确处置对象的用户,您可以将终结器用作后备,但它不能很好地用作清理对象的主要方法.为了顺利地工作,对象应该被正确处理,这样更昂贵的终结器就不需要被调用了.
You can use the Finalizer as a fallback for users who fail to dispose objects properly, but it doesn't work well as the primary method for cleaning up objects. To work smoothly objects should be disposed properly, so that the more costly Finalizer doesn't ever need to be called.
这篇关于Dispose,什么时候调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!