簡體   English   中英

如何將事件/異常從計時器事件處理程序返回到C#中的主線程?

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

我有Windows服務應用程序(沒有winforms)。 在Main方法中我啟動了計時器。 Timer elapsed事件處理程序在新線程(?)中運行。 有沒有簡單的方法如何將例程從經過時間的事件處理程序中拋出回主線程?

我試圖處理處理程序體中的異常並引發自定義事件,但是當我在上升此事件時重新啟動主進程時,現在運行2個進程同時執行相同的操作。

如何從定時事件處理程序線程返回主線程獲取事件或異常信息?

謝謝。

編輯:

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");
    }
}
}

這寫在控制台上:

Catch clause caught : 1
Throwing from timer event handler

然后使用未處理的異常對throw new Exception(“timer exception”)進行程序崩潰; 如果我取消注釋拋出新的異常(“2”); 處理執行並在控制台上也“捕獲Catch子句:2”。 換句話說,MyHandler不處理計時器異常。

您需要使用AppDomain.UnhandledException事件來訂閱所有異常事件。

編輯:根據MSDN:

在.NET Framework 2.0及更早版本中,Timer組件捕獲並抑制事件處理程序為Elapsed事件拋出的所有異常。 在將來的.NET Framework版本中,此行為可能會發生更改。

我使用dotPeek從.NET4查看了System.Timers.Timer的源代碼,自2.0以來仍然沒有變化,所以請考慮使用System.Threading.Timer。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM