.NET 2.0 : File.AppendAllText(…) - Thread safe implementation

前端 未结 3 2168
后悔当初
后悔当初 2021-02-13 05:46

As an exercise in idle curiosity more than anything else, consider the following simple logging class:

internal static class Logging
{
    private static object          


        
3条回答
  •  野的像风
    2021-02-13 06:37

    File.AppendAllText is going to acquire an exclusive write-lock on the log file, which would cause any concurrent thread attempting to access the file to throw an exception. So yes, you need a static lock object to prevent multiple threads from trying to write to the log file at the same time and raising an IOException.

    If this is going to be an issue, I'd really suggest logging to a database table which will do a better job of handling concurrent log writers.

    Alternatively, you can use TextWriterTraceListener which is thread-safe (well, it's going to do the locking for you; I'd rather write as little of my own multithreaded code as possible).

提交回复
热议问题