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 thei
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.