Search code examples
c#asynchronousstreamwriter

File used by another process - StreamWriter


I have checked all other solutions, nothing is working. I am calling an asynchronous logging method from different button events.

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);
    }
}

Log method uses 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;
    }
}

When I click on button1 and button2, the below exception is caught:

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


Solution

  • try something like this

     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 keyword will lock the stream writer till the current writer process is finished