Search code examples
c#filedisposeusingstreamwriter

Using the "using" statement with StreamWriter in C#


My application has a logger which constantly logs data in a number of different files. Logging in each file is done synchronously using a StreamWriter object inside a "using" block. From time to time, I get an exception saying the file I'm trying to open is being used by another process.

Now the files I log into each has a unique name associated with the client id. My application is multi-threaded, but at any point in time only 1 instance of the client is active, so I am sure that the same file is not opened by more than 1 thread. However, my application does logs in the same file multiple times in say less than 1 second, for each log attempting to reopen the file. This leaves me to one other conclusion, that the "using" statement does not immediately close the file (even though I've read that it does for files), but only disposes it and waits for the GC to handle the closing.

Is my conclusion correct or is it something else that's causing the exception?


Solution

  • After exiting the using statement not only call to Close is made, but also to Dispose, cause using is nothing else then syntax sugare for

    try {
      //do stuff 
    }
    finally {
     //close, dispose stream object
    }
    

    So the problem is in multithreaded access, that somehow tries to access a file whom writer not yet disposed, which does not mean that using statement does not work, but means that it still has to finish it job.

    EDIT

    You can try to use ProcessExplorer to check the specified file handle ownership. Check out online help for how to do it.