开发者

Do I need to call Dispose() on a static object?

If I have a static WebClient object, do I need to开发者_开发知识库 call Dispose() on it at the end of Main()?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜