另一个进程使用的文件 - StreamWriter

File used by another process - StreamWriter

我检查了所有其他解决方案,均无效。 我正在从不同的按钮事件调用异步记录方法。

private async void button1_Click(object sender, EventArgs e)
{
    await Task.Run(() => LoggerTest());
}

private async void button2_Click(object sender, EventArgs e)
{
    await Task.Run(() => LoggerTest());
}

private async void LoggerTest()
{
    for (int i = 0; i < 10000; i++)
    {
        Logger.Log(string.Format("Counter: {0}", i));
        Thread.Sleep(10);
    }
}

日志方法使用StreamWriter

private void Log(string log)
{
    if (!IsFileLocked(fullPath))
    {
        using (StreamWriter file = new StreamWriter(fullPath, append: true))
        {
            file.WriteLine(log);
            file.Close(); // I know this is unnecessary in the using block
        }
    }
}

private bool IsFileLocked(string file)
{
    try
    {
        using (var stream = File.OpenRead(file))
            return false;
    }
    catch (IOException)
    {
        return true;
    }
}

当我点击 button1 和 button2 时,捕获到以下异常:

System.IO.IOException: 'The process cannot access the file 'C:..\x.txt' because it is being used by another process.'

尝试这样的事情

 private static readonly object locker = new object();
lock (locker)
            {
                using (FileStream fileStream = new FileStream("FilePath"), FileMode.Append))
                {
                    using (StreamWriter writer = new StreamWriter(fileStream))
                    {
                        writer.WriteLine(log);
                    }
                }
            }

lock 关键字将锁定流写入器,直到当前写入器进程完成