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 ()?

+4
source share
2 answers

You should always Dispose() objects when you finish with them, no matter where you place the object.

If the object is in a static field, it can be harder to figure out when you are done with it.

+5
source

As a rule, you should dispose of any disposable items. This will allow them to clear any resources. However, there is no guarantee that a dispose will be called by a one-time type β€” the consumer can neglect its call, and the CLR does not automatically call it.

If the type really needs cleanup logic to execute (for example, when allocating unmanaged memory or creating a bunch of files in the file system), it must implement a finalizer in combination with a layout template. The CLR will call the finalizer when exiting the process, if it has not already been called (usually by deleting the object). Yes, there are some caveats around this (for example, a bad finalizer can ruin the party for other finalizable instances), but the CLR guarantees at least an attempt to start all finalizers upon exiting the process.

So, technically, I see no reason why you should call the dispose method in this case. However, it is a good habit to enter nevertheless.

+2
source

All Articles