Writing to file in a thread safe manner

后端 未结 2 1437
忘了有多久
忘了有多久 2020-12-05 04:48

Writing Stringbuilder to file asynchronously. This code takes control of a file, writes a stream to it and releases it. It deals with requests from asynchronous

2条回答
  •  情话喂你
    2020-12-05 04:55

    You could also use ReaderWriterLock, it is considered to be more 'appropriate' way to control thread safety when dealing with read write operations...

    To debug my web apps (when remote debug fails) I use following ('debug.txt' end up in \bin folder on the server):

    public static class LoggingExtensions
    {
        static ReaderWriterLock locker = new ReaderWriterLock();
        public static void WriteDebug(string text)
        {
            try
            {
                locker.AcquireWriterLock(int.MaxValue); 
                System.IO.File.AppendAllLines(Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", ""), "debug.txt"), new[] { text });
            }
            finally
            {
                locker.ReleaseWriterLock();
            }
        }
    }
    

    Hope this saves you some time.

提交回复
热议问题