[英]Accessing Variables Created In Application_Start ASP.NET MVC 3
[英]ASP.net Application_Start catch exception in timer
給定Global.asax
的以下代碼,可以正確捕獲引發的第一個異常,但不能捕獲計時器異常。
我需要更改什么以捕獲計時器中的任何異常?
protected void Application_Start(object sender, EventArgs e)
{
// THIS WORKS
try
{
throw new Exception("Test!");
}
catch (Exception ex)
{
Code.Helpers.Error.Functions.RecordError(ex);
}
// THIS DOESN'T WORK
try
{
var myTimer = new Timer(
Code.Helpers.MyTimer.Process,
null,
new TimeSpan(0, 0, 0, 0),
Settings.ProcessMyTimerEvery);
}
catch (Exception ex)
{
Code.Helpers.Error.Functions.RecordError(ex);
}
}
從System.Threading.Timer
文檔(重點是我的):
提供一種機制,用於以指定的時間間隔在線程池線程上執行方法。
這也是值得一讀此 :
為回調指定的方法應該是可重入的,因為它是在ThreadPool線程上調用的。 如果計時器間隔小於執行該方法所需的時間,或者所有線程池線程都在使用中並且該方法多次排隊,則可以在兩個線程池線程上同時執行該方法。
這意味着您傳遞給計時器的委托不會在計時器所在的同一線程上調用。 要在計時器事件中捕獲異常,您需要在其中放置try / catch。 例如:
var myTimer = new Timer(
TimerEvent, //<-- A delegate to the TimerEvent method
null,
new TimeSpan(0, 0, 0, 0),
new TimeSpan(0, 0, 0, 5));
和您的計時器代碼:
private void TimerEvent(object x)
{
try
{
throw new Exception("Exception in timer event");
}
catch (Exception ex)
{
Code.Helpers.Error.Functions.RecordError(ex);
}
}
您應該將try
/ catch
塊放置在計時器回調中(在您的情況下為Code.Helpers.MyTimer.Process
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.