Simple MultiThread Safe Log Class

后端 未结 5 551
轻奢々
轻奢々 2021-01-02 01:26

What is the best approach to creating a simple multithread safe logging class? Is something like this sufficient? How would I purge the log when it\'s initially created?

5条回答
  •  醉话见心
    2021-01-02 01:58

    The question uses File.AppendText which is not an asynchronous method, and other answers correctly show that using a lock is the way to do it.

    However, in many real-world cases, using an asynchronous method is preferred so the caller doesn't have to wait for this to get written. A lock isn't useful in that case as it blocks the thread and also async methods are not allowed inside the lock block.

    In such situation, you could use Semaphores (SemaphoreSlim class in C#) to achieve the same thing, but with the bonus of being asynchronous and allowing asynchronous functions to be called inside the lock zone.

    Here's a quick sample of using a SemaphoreSlim as an asynchronous lock:

    // a semaphore as a private field in Logging class:
    private static SemaphoreSlim semaphore = new SemaphoreSlim(1, 1);
    
    // Inside WriteToLog method:
    try 
    {
        await semaphore.WaitAsync();
    
        // Code to write log to file asynchronously
    }
    finally
    {
        semaphore.Release();
    }
    

    Please note that it's good practice to always use semaphores in try..finally blocks, so even if the code throws an exception, the semaphore gets released correctly.

提交回复
热议问题