0

I have a small logger class that just contains some static helper methods for easily writing to a log file. I wanted to test how robust it was, so I attempted to run it asynchronously 100 times at once.

[TestMethod]
public void Diagnostics_AsyncWritePass()
{
    int linesToWrite = 100;
    String logMsg = "Async test log ";
    List<Task> asyncTaskList = new List<Task>();

    for (int i = 0; i < linesToWrite; i++)
    {
        Task task = new Task(() => Logger.Info(logMsg + i));
        asyncTaskList.Add(task);
        task.Start();
    }

    Task.WaitAll(asyncTaskList.ToArray());

    List<String> lines = GetLastLogLines(linesToWrite);

    foreach (String line in lines)
    {
        Assert.IsTrue(line.Contains(logMsg));
    }
}

The actual logging (inside the Logger.Info method) is performed using:

File.AppendAllText(LogPath, logMsg + Environment.NewLine);

The GetLastLogLines method is:

private List<String> GetLastLogLines(int numLines)
{
    List<String> lines = File.ReadLines(Logger.LogPath)
        .Reverse()
        .Take(numLines)
        .ToList();
    return lines;
}

However, I have two issues with this.

  • The first is that it is not writing 100 lines, it is writing around 90.
  • The second is that every line is Async test log 100 - the number does not increment every line. I'm guessing that the i counter is being passed by reference, not by value.

Why might these problems occur?

EDIT: The incorrect number of lines issue was solved by replacing the contents of GetLastLogLines. Previously, it was using File.ReadLines then using LINQ to take only x number of lines. Instead, I used this answer and it returned the correct number of lines.

Mike Baxter
  • 6,868
  • 17
  • 67
  • 115

1 Answers1

0

Your second problem is standard issue when a lambda expression captures an iteration variable.

Make the following change.

for (int i = 0; i < linesToWrite; i++)
{
    var t = i;
    Task task = new Task(() => Logger.Info(logMsg + t));
    asyncTaskList.Add(task);
    task.Start();
}

Can you show us what GetLastLogLines() does?

Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32