Write to a file from multiple threads asynchronously c#

后端 未结 7 1626
忘掉有多难
忘掉有多难 2020-12-02 14:04

Here is my situation. I would like to make writing to the file system as efficient as possible in my application. The app is multi-threaded and each thread can possibly wr

7条回答
  •  半阙折子戏
    2020-12-02 15:02

    For those who prefer code, I am using following to do remote logging from web apps...

    public static class LoggingExtensions
    {
        static ReaderWriterLock locker = new ReaderWriterLock();
        public static void WriteDebug(this string text)
        {
            try
            {
                locker.AcquireWriterLock(int.MaxValue); //You might wanna change timeout value 
                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

提交回复
热议问题