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

こ雲淡風輕ζ 提交于 2019-12-05 15:35:58

问题


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

internal static class Logging
{
    private static object threadlock;

    static Logging()
    {
        threadlock = new object(); 
    }

    internal static void WriteLog(string message)
    {
        try
        {
            lock (threadlock)
            {
                File.AppendAllText(@"C:\logfile.log", message);
            }
        }
        catch
        {
            ...handle logging errors...
        }
    }
}

Is the lock needed around File.AppendAllText(...) or is the method inherently thread-safe by its own implementation ?

Searching for information on this yields a lot of contradictory information, some say yes, some say no. MSDN says nothing.


回答1:


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).




回答2:


Testing parallel writes shows that you would get a System.IO.IOException if you were to comment out your lock statement.

[Test]
public void Answer_Question()
{
    var ex = Assert.Throws<AggregateException>(() => Parallel.Invoke(
        () => Logging.WriteLog("abc"),
        () => Logging.WriteLog("123")
    ));

    // System.IO.IOException: The process cannot access the file 'C:\Logs\thread-safety-test.txt' because it is being used by another process.
    Console.Write(ex);
}



回答3:


It is thread safe in the sense that it opens the file with Read sharing, so assuming your filesystem honors file locks, only one thread will be allowed to write to the file at a time. Other threads may, however, get dirty reads if they are attempting to read the same file.



来源:https://stackoverflow.com/questions/4809843/net-2-0-file-appendalltext-thread-safe-implementation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!