Search code examples
c#memory-managementmemory-leaksdisposeresource-management

Static variable that will not be disposed


I have a static StreamWriter variable in my class:

private static StreamWriter streamWriter = CreateStreamWriter(pathToFile);

I am not closing this StreamWriter in my app since it needs to be open while the app is running.

If I start and stop this app many many times, will I get a memory leak? Or is the object disposed of properly upon closing the app?

This class is a utility class used by both ASP.NET MVC 4 and WPF apps.

Thanks to all for your responses. Here is the code I added:

In the class containing the StreamWriter:

public static void OnApplicationExit(object sender, EventArgs e)
{
    try
    {
        streamWriter.Flush();
        streamWriter.Close();
        streamWriter.Dispose();
    }
    catch { }
}

public static void OnApplicationExit()
{
    try
    {
        streamWriter.Flush();
        streamWriter.Close();
        streamWriter.Dispose();
    }
    catch { }
}

And in ASP.NET MVC Global.Asax:

    protected void Application_End()
    {
        Utilities.MyClass.OnApplicationExit();
    }

Solution

  • The StreamWriter is not guaranteed to be disposed when the application closes. Sometimes it will, but in some situations that's not possible.

    There is no memory leak, as it uses managed memory. The entire heap is removed when the application closes.

    It's not a resource leak either, as the open file handles will be closed when the application is shut down.

    However, the StreamWriter has a buffer that is not flushed if it's not disposed. That means that the last things that you wrote using the writer may be missing from the file.