I have windows service application (no winforms). In Main method I started timer. Timer elapsed event handler is running in new thread(?). Is any easy way how to throw exceptions from timer elapsed event handler back to main thread?
I was trying to handle exceptions in handler body and rise custom events, but when I restart the main process on rising this event, now runs 2 processes doing same things simultaneously.
How can I get event or exception information form timer event handler thread back to main thread?
Thank you.
EDIT:
using System;
using System.Security.Permissions;
using System.Timers;
namespace TestingConsoleApplication.Model
{
static class ThreadExceptionTester
{
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
public static void Run()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
Timer Timer = new Timer(1000);
Timer.Elapsed += new ElapsedEventHandler(TimerEventHandler);
Timer.Start();
try
{
throw new Exception("1");
}
catch (Exception e)
{
Console.WriteLine("Catch clause caught : " + e.Message);
}
//throw new Exception("2");
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception)args.ExceptionObject;
Console.WriteLine("MyHandler caught : " + e.Message);
}
static void TimerEventHandler(object source, ElapsedEventArgs e)
{
Console.WriteLine("Throwing from timer event handler");
throw new Exception("timer exception");
}
}
}
This write on console this:
Catch clause caught : 1
Throwing from timer event handler
And then program crash with unhandled exception on throw new Exception(“timer exception”); If I uncomment throw new Exception(“2”); Exeption is processed and on console is also “Catch clause caught : 2”. In other words, timer exceptions are not processed by MyHandler.
You need to use AppDomain.UnhandledException event for subscribing to all exception events.
EDIT:
According to MSDN:
i have looked into source of System.Timers.Timer from .NET4 using dotPeek and there still no changes since 2.0, so consider using System.Threading.Timer instead.