简体   繁体   English

如何使用async / await以线程安全的方式从多个线程异步写入文件流

[英]how to write to a file stream asynchronously using async/await from multiple threads in a thread-safe manner

I have an extremely simple logging utility that is currently synchronous. 我有一个非常简单的日志记录实用程序,当前正在同步。 It gets called from UI (WPF) and threadpool threads (Task.Run) and uses lock(_stream){_stream.WriteLine(message);} for thread safety. 它从UI(WPF)和线程池线程(Task.Run)中调用,并使用lock(_stream){_stream.WriteLine(message);}来保证线程安全。 I'd like to add an asynchronous write method but not sure how to make it threadsafe. 我想添加一个异步写入方法,但不确定如何使其成为线程安全的。

  1. Will the following async method work? 以下异步方法可以工作吗?
  2. Will it play nice with the existing synchronous method and can they be used together without issues? 它可以与现有的同步方法配合使用,并且可以将它们一起使用而不会出现问题吗?
  3. Assuming the previous is resolved, should the final Debug.WriteLine go inside the try block or after the finally where it currently is - does it make a difference? 假设前面的命令已解决,那么最终的Debug.WriteLine应该放在try块中还是放在当前当前的finally位置之后-会有所作为吗?
private static SemaphoreSlim _sync = new SemaphoreSlim(1);    

public static async Task WriteLineAsync(string message)
{
    if (_stream != null)
    {
        await _sync.WaitAsync();

        try
        {
            await _stream.WriteLineAsync(string.Format("{0} {1}", DateTime.Now.ToString("HH:mm:ss.fff") + message));
        }
        catch(Exception ex)
        {
            Debug.WriteLine(ex.ToString());
        }
        finally
        {
            _sync.Release();
        }

        Debug.WriteLine("{0} {1}", DateTime.Now.ToString("HH:mm:ss.fff"), message);
    }
}

Will the following async method work? 以下异步方法可以工作吗?

If the stream is set up properly, then yes, i see no reason why it wouldn't 如果流设置正确,那么是的,我没有理由不这样做

Will it play nice with the existing synchronous method and can they be used together without issues? 它可以与现有的同步方法配合使用,并且可以将它们一起使用而不会出现问题吗?

If your synchronous methods use the same SemaphoreSlim and use the synchronous Wait , they should play along nicely. 如果您的同步方法使用相同的SemaphoreSlim并使用同步Wait ,那么它们应该很好地配合使用。

Assuming the previous is resolved, should the final Debug.WriteLine go inside the try block or after the finally where it currently is - does it make a difference? 假设前面的命令已解决,那么最终的Debug.WriteLine应该放在try块中还是放在当前当前的最后位置之后-会有所作为吗?

If the debug message should be written if and only if the stream successfully writes a message to the stream, it should be inside your try block, after the call to WriteLineAsync . 如果仅在流成功向流中写入消息时才应编写调试消息,则该消息应位于调用WriteLineAsync之后的try块内。

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

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