2012-10-30 67 views
1

我正在使用Threading.Timer來每小時執行一個小時的任務,但是當計時器滴答時,應用程序在處理代碼時會一直崩潰。它沒有任何例外或警告而崩潰,即使我將整體細化爲try/catch。很奇怪。以下是我的設置和任何幫助,將不勝感激!它似乎像試圖訪問TextBox GrepCmdTextBox時崩潰,但我認爲從另一個線程閱讀是好的,只是不寫。Threading.Timer崩潰我的Winform應用程序?

設置定時器:

var timeOfDay = DateTime.Now.TimeOfDay; 
var nextHour = TimeSpan.FromHours(Math.Ceiling(timeOfDay.TotalHours)); 
var delta = (nextHour - timeOfDay).TotalMilliseconds; 
System.Threading.Timer NextHourTimer = new System.Threading.Timer(new System.Threading.TimerCallback(NextHourTimer_Tick), null, (long)delta, (long)TimeSpan.FromHours(1).TotalMilliseconds); 

Tick事件:

private void NextHourTimer_Tick(object sender) 
    { 
     // If thread is not null and is busy, cancel and restart 
     if (MonitoringThread != null) 
     { 
      if (MonitoringThread.TailThread.IsBusy) 
      { 
       MonitoringThread.TailThread.CancelAsync(); 
       System.Threading.Thread.Sleep(50); 

       // Get grep command, if specified 
       string optionalGrep = String.Empty; 
       if (GrepCmdTextBox.Text.StartsWith("grep") || GrepCmdTextBox.Text.StartsWith("egrep")) 
        optionalGrep = " | " + GrepCmdTextBox.Text; 

       MonitoringThread.TailThread.RunWorkerAsync(optionalGrep); 
      } 
     } 
    } 
+0

運行時必須拋出_some_異常。啓用拋出的所有異常,並告訴我們它在做什麼... – MoonKnight

+0

@Killercam我不知道男人,我什麼也沒有看到......在哪裏可以啓用所有例外的選項? – Hershizer33

+0

如果您使用的是VS2010,那麼首先您可以對菜單'調試'>'例外...'中的任何異常啓用自動投擲。然後檢查所有CLR異常並重新運行代碼。添加您可能認爲相關的其他例外。如果這不起作用,這可能是一個非託管代碼異常。這一次,請轉到您的項目屬性,然後在「調試」選項卡上;勾選'啓用非託管代碼調試' - 然後告訴我們你看到了什麼:在這一點上,我可以(或不可以!)能夠進一步幫助你... – MoonKnight

回答

2

取消異步過程可能需要一段時間,後臺線程將要 '完成',從DoWork的回國()並等待機會運行RunWorkerCompleted事件(如果有的話)。

而不是取消,在這種情況下,最好是取消然後Dispose()這個對象,創建一個新的BGW,因爲它們就像'芯片便宜'一樣。

我希望這會有所幫助。