简体   繁体   English

.NetCore - 使用 Semaphoreslim 的异步记录器

[英].NetCore - Async Logger using Semaphoreslim

I am trying to create a logic based on requirements below.我正在尝试根据以下要求创建逻辑。

  • The class should output to a file class应该output到一个文件
  • The class must preserve the order of the messages class 必须保留消息的顺序
  • Calling Log does not block calling thread调用日志不会阻塞调用线程
  • Calling Log must be thread safe (will be called from multiple threads)调用 Log 必须是线程安全的(会被多线程调用)

Sample code i tried is below我试过的示例代码如下

 Ilogger log = new Logger();

Thread t1 = new Thread(LongRunningTask);
Thread t2 = new Thread(LongRunningTask2);
t1.Start();
t2.Start();

Console.WriteLine("Hello, World!");

async void LongRunningTask()
{

    for (int i = 0; i < 10; i++)
    {
        await log.Info("Thread-1 - " + i.ToString());
    }

}

async void LongRunningTask2()
{

    for (int i = 0; i < 10; i++)
    {
        await log.Info("Thread-2 - " + i.ToString());
    }

}

Logger Concrete class implementation记录器具体 class 实现

internal class Logger : Ilogger
    {
        SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1);
        public async Task Info(string message)
        {
            
            try
            {
                await semaphoreSlim.WaitAsync();
                Console.WriteLine(message);
                
                //await File.WriteAllTextAsync("C://test.txt", message);
            }
            finally
            {
                semaphoreSlim.Release();
            }
        }

    }

Console output seems to be fine.控制台 output 似乎没问题。 I am getting messages in order.我正在按顺序收到消息。 But if i tried to write to a file am getting error as但是,如果我尝试写入文件,则会出现错误

The process cannot access the file 'C:\test.txt' because it is being used by another process该进程无法访问文件“C:\test.txt”,因为它正被另一个进程使用

Can anyone help me understand what I am doing wrong here?谁能帮助我了解我在这里做错了什么?

Update:更新:

Actually the problem is with File.WriteAllText - it will override what's already in. Replaced with实际上问题出在 File.WriteAllText - 它将覆盖已经存在的内容。替换为

File.AppendAllTextAsync - working fine now File.AppendAllTextAsync - 现在工作正常

Try using this to create your SemaphoreSlim尝试使用它来创建您的 SemaphoreSlim

SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1,1);

This basically works as a mutex now - allowing only one thread at a time.现在这基本上可以作为互斥体使用——一次只允许一个线程。

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

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