Okay, rather an odd one here that I couldn't really think of a good title for.
I've written an EventLog class that, under the circumstance of the application being UserInteractive rather than an installed service, writes event logs to the console window. If the application is not UserInteractive, it writes to the windows event log as expected
Because multiple tasks are using the EventLog at once, and there's some changing of colours going on, I've had to use a lock
so that there are no race conditions
public class EventLog : System.Diagnostics.EventLog
{
private static object consoleLock = new object();
public new static void WriteEntry(string source, string message, EventLogEntryType type)
{
if (!WriteToConsole(message, type))
{
System.Diagnostics.EventLog.WriteEntry(source, message, type);
}
}
private static bool WriteToConsole(string message, EventLogEntryType type)
{
if (!Environment.UserInteractive) return false;
Task.Run(() =>
{
lock (consoleLock)
{
Console.ForegroundColor = PickConsoleColour(type);
Console.Out.WriteLine("{0}: {1}", type.ToString(), message);
Console.ResetColor();
}
}).ConfigureAwait(false);
return true;
}
private static ConsoleColor PickConsoleColour(EventLogEntryType type)
{
switch (type)
{
case EventLogEntryType.SuccessAudit:
return ConsoleColor.Green;
case EventLogEntryType.Information:
return ConsoleColor.Cyan;
case EventLogEntryType.FailureAudit:
return ConsoleColor.DarkRed;
case EventLogEntryType.Warning:
return ConsoleColor.Yellow;
case EventLogEntryType.Error:
return ConsoleColor.Red;
default:
return ConsoleColor.Gray;
}
}
}
The reason I'm setting off fire & forget tasks is because I don't want all the calls to EventLog to block if there are a lot of messages that are trying to be printed to the console. I don't care about the order the messages come out in, either - so I don't need a queue or anything like that.
So the application runs like so: every couple of minutes, many new tasks are created, all of which might be writing to the EventLog.
It'll seemingly work fine for a long time, but after so long (around 30 minutes? I haven't timed it), messages will stop being printed to the console and the thread count of the process grows and grows
What I think is happening is for some reason the lock isn't being released, so lots of new fire & forget tasks are being created that are blocked by the lock. I can't figure out what's causing this to happen, but as soon as I press any key on the console window - boom - all the messages come through at once and everything starts working.