Steve Steve - 1 year ago 45
C# Question

Do I need to Dispose static objects which lives the whole life span of the application?

Lets say I want to do some logging, the first thing I would do is opening up a

to write to.

I would like to reuse the same stream for the application instead of opening and closing the stream for each log entry

This means the stream will live as long as the application.

something like

public static class Logger
static StreamWriter SW;

Now the question is, do I need to make a close method which would
SW and call it some where like

I feel GC would be able to do its job right and free SW when the application ends. But I want to make sure not doing so won't cause the application to hang in some special situations.

Answer Source

... the answer said all the resource will be free by the OS when app shuts down.

True, but just because a resource is freed does not mean it was freed in a clean manner.

You need to dispose of StreamWriter because it does not flush it's data immediately by default. If you do not Close/Dispose of it before your application is shut down the last bit of text will not be written out.

class Program
    static StreamWriter SW = new StreamWriter("test.txt");
    static void Main()

The text file will not contain the word Test after running the above program.

If you added SW.AutoFlush = true; to the program you would be fine with not disposing of it. But you need to be aware of limitations like this when dealing with any class that implements IDisposeable