Synchronizing thread access and write in C#

前端 未结 1 356
轮回少年
轮回少年 2021-01-16 03:56

I have a multithreaded port scanner app written in C#, and I want to print some stuff both to the console and a log file as the app runs. For this reason, I have the followi

相关标签:
1条回答
  • 2021-01-16 04:09

    Using a single file and a lock strategy should do the job:

    private Object m_Lock = new Object();
    
    public static void WriteLine(string str)
    {
        lock (m_Lock)
        {
            Console.WriteLine(str);
            OutputSingleton.SW.WriteLine(str);
        }
    }
    
    public static void Write(string str)
    {
        lock (m_Lock)
        {
            Console.Write(str);
            OutputSingleton.SW.Write(str);
        }
    }
    
    private void InstantiateStreamWriter()
    {
        string logFilename = "Log.txt";
        string filePath = Path.Combine(LogDirPath, logFilename);
    
        try
        {
            SW = new StreamWriter(filePath);
            SW.AutoFlush = true;
        }
        catch (UnauthorizedAccessException ex)
        {
            throw new ApplicationException(string.Format("Access denied. Could not instantiate StreamWriter using path: {0}.", filePath), ex);
        }
    }
    

    The problem here comes with the shared lock. If you use the same lock on multiple methods, then locking one method locks other methods as well (in your case Write and WriteLine). It looks totally fine to me since they are strictly related... but this may create a bottleneck if the methods are called very frequently. On the other side, separate locks would make the methods run independently and this is even worse.

    Try to merge the two methods into one as follows, so you don't have to care about handling locks on separate methods:

    public static void WriteLine(String str, Boolean line = true)
    {
        lock (m_Lock)
        {
            if (line)
            {
                Console.WriteLine(str);
                OutputSingleton.SW.WriteLine(str);
            }
            else
            {
                Console.Write(str);
                OutputSingleton.SW.Write(str);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题