问题
I have a singleton logger which is used inside an ASP.NET application. Sometimes I get The process cannot access the file
error on this line:
StreamWriter sw = new StreamWriter("Path to log file", true);
I checked file handle by Process Explorer and w3wp.exe
owns the handle so it seems different threads from the same process caused the problem.
I have used a lock
around the above code, but still I get the error.
How can I make sure all threads can use the same stream safely?
回答1:
Don't open the log file more than once; just open it when the application starts, close it at exit (and flush it often.) Opening and closing more than once is just inefficient.
来源:https://stackoverflow.com/questions/6092421/the-process-cannot-access-the-file-c-inetpub-wwwroot-myapp-5-23-2011-log-beca