Are Timers in .NET safe to abandon without calling Dispose() or Close()?
static System.Timers.Timer timer = new Timer();
void Main()
{
timer.Elapsed += LogTimer_Elapsed(object, System.Timers.ElapsedEventArgs);
timer.Start();
Thread.Sleep(10000); // Simulate doing something on main thread
}
static void LogTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
DoStuff();
}
Anyone see any problems with this solution?
static QueueLogger()
{
LogQueue = new Queue<KeyValuePair<Logger, LogEntry>>(50);
LogTimer = new Timer();
LogTimer.Elapsed +=new System.Timers.ElapsedEventHandler(LogTimer_Elapsed);
AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
}
static void CurrentDomain_ProcessExit(object sender, EventArgs e)
{
LogTimer.Stop();
LogTimer.Dispose();
LogTimer_Elapsed(sender, null); // This is to process any remaining messages in the queue
}
static void LogTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
lock (_locker)
{
while (LogQueue.Count > 0)
{
var queuedLogger = LogQueue.Dequeue();
try
{
if (e != null) queuedLogger.Value.Message += " From " + sender.ToString();
queuedLogger.Key.Log(queuedLogger.Value);
}
catch (Exception ex)
{
OnLoggingError(queuedLogger.Key, "Async Logging error", ex);
}
}
}
}
Galford,
Yes, you can create new event which will fire if your application is about to exit e.g. OnExit and listen to the event when you application’s main thread is about to close. Once that is done you can create event logic and do your timer, business or clean up logic in OnExit event. Hope this helps.
Regards