简体   繁体   English

C#多线程日志记录-无锁定

[英]c# multi-threaded logging - no locking

I have created a Logging utility class for my multithreaded C# app. 我为我的多线程C#应用程序创建了一个日志实用程序类。 In order to ensure safe access to the file by all threads, I am locking on a static object as follows: 为了确保所有线程对文件的安全访问,我将静态对象锁定如下:

    private static readonly object locker = new object();

    public static void WriteLog(String message, params Object[] args)
    {
        try
        {
            string filename = m_baseDir + GetFilenameYYYMMDD("_LOG", ".log");
            lock (locker)
            {
                System.IO.StreamWriter sw = new System.IO.StreamWriter(filename, true);
                String msg = String.Format(message, args);
                sw.WriteLine(System.DateTime.Now.ToString() + " -" + msg);
                sw.Close();

            }
        }
        catch (Exception ex) { Console.WriteLine(ex); }
    }

However, when my application runs, I am still getting a System.IO.Exception on the line that initialises the sw variable. 但是,当我的应用程序运行时,仍然在初始化sw变量的行上出现System.IO.Exception

System.IO.IOException: The process cannot access the file 'C:\\MyApp\\bin\\Debug\\Logs\\MyApp_2017_09_18_LOG.log' because it is being used by another process. System.IO.IOException:进程无法访问文件'C:\\ MyApp \\ bin \\ Debug \\ Logs \\ MyApp_2017_09_18_LOG.log',因为该文件正在由另一个进程使用。 at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) 在System.IO .__ Error.WinIOError(Int32 errorCode,可能是StringFullPath)

I do get messages in the Log though, so some thread(s) must be able to write to the file. 我确实在日志中收到消息,因此某些线程必须能够写入文件。

How can I fix this so all threads can access the file? 如何解决此问题,以便所有线程都可以访问文件?

I got the same problem like before: 我遇到了和以前一样的问题:

I just use this: 我只是用这个:

        sw.Flush();
        sw.Close();

After the execution has done. 执行完成后。

You can try this sw.Dispose(); 你可以试试这个sw.Dispose(); also. 也。

Hope it helps: 希望能帮助到你:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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