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

前端 未结 3 2156
后悔当初
后悔当初 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:47

    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(() => 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);
    }
    

提交回复
热议问题