简体   繁体   中英

C# File Open frequently, already open exception

Hey so I have a logger class that is called frequently, sometimes when its called fast repeatedly it will throw an exception that the file is already open being used by another application. The only way we found a way around this was to catch the exception then try to open it again... I'm not sure how to handle this properly.

    /// <summary>
    /// Open a log file based on a date
    /// </summary>
    /// <param name="date"> Date of the file to open </param>
    public static void OpenLogFile(DateTime date)
    {
        while (true)
        {
            try
            {
                logStream = File.Open("Logs/ems." + date.ToString("yyyy-MM-dd") + ".log", FileMode.Append);
                break;
            }
            catch
            {
                continue;
            }
        }
    }




    /// <summary>
    /// Writes to a log file the specified input
    /// </summary>
    /// <param name="input"> Content to write to the log file </param>
    public static void Log(string className, string methodName, string input)
    {
            OpenLogFile(DateTime.Now);

            using (StreamWriter s = new StreamWriter(logStream))
            {
                s.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + '[' + className + '.' + methodName + "] " + input);
            }

            CloseLogFile(); 
    }




    /// <summary>
    /// Closes the current log file
    /// </summary>
    public static void CloseLogFile()
    {
        if (logStream != null)
        {
            logStream.Close();
            logStream = null;
        }
    }

Since this is a log file, I think the obvious (and correct) solution, is to leave the file open for the duration of your program's execution.

If you don't want to use an already-implemented 3rd party logger, like Apache's log4net , you could write your own little logger class that uses thread-safe mechanisms for writing lines to the file.

It would probably be a static class, or singleton. Generally, execution at the beginning and end of your program is quite predictable, so it should be clear where to initialize, and close out the object/class.

A bit of order is required, not a disk free-for-all. Store log messages in a queue and have a single thread dequeue and write items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM