private static void WriteLogEntriesToFile()
{
while(!StopLoggingRequested)
{
// Get next log entry from queue
XElement xmlEntry = Peek();
if(xmlEntry == null)
{
// If queue is empty, sleep for a while and look again later.
Thread.Sleep(100);
continue;
}
// Try ten times to write the entry to the log file. Wait between tries, because the file could (hopefully) temporarily
// be locked by another application. When it didn't work out after ten tries, dequeue the entry anyway, i.e. the entry is lost then.
// This is necessary to ensure that the queue does not get too full and we run out of memory.
for(int i = 0; i < 10; i++)
{
// Actually write entry to log file.
LastExceptionInBackgroundTask = WriteLogEntryToFile(xmlEntry);
// When all is fine, we're done. Otherwise do not retry when queue is already getting full.
if(LastExceptionInBackgroundTask == null || NumberOfLogEntriesWaitingToBeWrittenToFile > 1000)
break;
// Only wait when queue is not already getting full.
Thread.Sleep(100);
}
// Dequeue entry from the queue
Dequeue();
}
}