black
black

Reputation: 810

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?

Upvotes: 0

Views: 2388

Answers (3)

Tigran
Tigran

Reputation: 62266

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.

Upvotes: 2

Ankur
Ankur

Reputation: 33647

The using statement will call the Dispose on the FileStream which will immediately release the underlying file handle. Your issue is due to overlapping in file writes.

Upvotes: 0

Andrew Barber
Andrew Barber

Reputation: 40150

Your conclusion is incorrect. Once closed with Close or Dispose (or exiting a using block), you can then immediately reopen the file in another using block.

There has to be some other thread using the file.

Upvotes: 0

Related Questions