简体   繁体   中英

How to get event/exception from timer event handler back to main thread in C#?

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:

In the .NET Framework version 2.0 and earlier, the Timer component catches and suppresses all exceptions thrown by event handlers for the Elapsed event. This behavior is subject to change in future releases of the .NET Framework.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM