Writing a log to the lock for edit file, which throws an exception. How to fix it?

I have multithreaded work, each of which adds some information to the log file. The problem is that sometimes the log file is locked for editing and at the same time is accessible by another thread that throws an exception. How can I make sure the magazine is spelled correctly?

here is a fragment

 try
 {
  File.AppendAllText(fileName, appendString);
 }
 catch (System.Exception )
 {
 }

I just ignore the exception. this causes some logs to not be recorded.

+3
source share
2 answers

You need to sync log entries.

What happens is that two threads join the log file at the same time.

Try the following:

class Program
{
    public static readonly object LogWriteLock = new object();

    // The rest of your Program class.
}

:

lock (Program.LogWriteLock)
{
    File.AppendAllText(fileName, appendString);
}

, . (Program.LogWriteLock), "" . , , .

, - :

public static class LogHelper
{
    private static readonly object _syncRoot = new object();

    public static void AppendToLog(string appendString)
    {
        lock (_syncRoot)
        {
            File.AppendAllText("log.txt", appendString);
        }
    }
}

"log.txt" .

+6

, , , ?

, .

0

Source: https://habr.com/ru/post/1773682/


All Articles