How do I lock the console across threads in C#.NET?

前端 未结 1 1246
我寻月下人不归
我寻月下人不归 2020-12-30 09:23

I have a logger class that handles various information display with pretty colors (yay.). However, since it writes to the console in separated steps

相关标签:
1条回答
  • 2020-12-30 09:44

    Your class needs:

    private static readonly object ConsoleWriterLock = new object();
    

    Then you can lock on this before writing to the console.

    lock(ConsoleWriterLock)
    {
         //Your code here
    }
    

    The lock keyword will work with a static class, you just need to provide a static readonly object to lock on.

    0 讨论(0)
提交回复
热议问题