2011-02-04 50 views
1

在我的網站中,我使用一個線程來執行後臺進程。我點擊按鈕啓動線程。ASP.NET中的線程超時問題

現在我面臨的問題是,它似乎超時停止。基本上它停止更新數據庫。

什麼可能是錯的?

這裏是我的代碼:

public static class BackgroundHelper 
{ 
    private static readonly object _syncRoot = new object(); 
    private static readonly ManualResetEvent _event = new ManualResetEvent(false); 
    private static Thread _thread; 
    public static bool Running 
    { 
     get; 
     private set; 
    } 
    public static void Start() 
    {  
     lock (_syncRoot) 
     { 
      if (Running) 
       return; 
      Running = true; 
      // Reset the event so we can use it to stop the thread. 
      _event.Reset(); 
      // Star the background thread. 
      _thread = new Thread(new ThreadStart(BackgroundProcess)); 
      _thread.Start(); 
     } 
    } 

    public static void Stop() 
    { 
     lock (_syncRoot) 
     { 
      if (!Running) 
       return; 
      Running = false; 
      // Signal the thread to stop. 
      _event.Set(); 
      // Wait for the thread to have stopped. 
      _thread.Join(); 
      _thread = null; 
     } 
    } 

    private static void BackgroundProcess() 
    { 
     int count = 0; 
     DateTime date1 = new DateTime(2011, 2, 5); 
     while (System.DateTime.Compare(System.DateTime.Now, date1) < 0) 
     { 
      downloadAndParse(); 
      // Wait for the event to be set with a maximum of the timeout. The 
      // timeout is used to pace the calls to downloadAndParse so that 
      // it not goes to 100% when there is nothing to download and parse. 
      bool result = _event.WaitOne(TimeSpan.FromSeconds(45)); 
      // If the event was set, we're done processing. 
      // if (result) 
      // break; 
      count++; 
     } 
    } 

    private static void downloadAndParse() 
    { 
     NewHive.MyServ newServe = new NewHive.MyServ(); 
     NewHive.CsvDownload newService = new NewHive.CsvDownload(); 
     //NewHive.MyServ newServe = new NewHive.MyServ(); 
     string downloadSuccess = newService.CsvDownloader(); 
     if (downloadSuccess == "Success") 
     { 
      string parseSuccess = newService.CsvParser(); 

     } 
     newServe.updateOthersInPosition(); 
    } 
} 

回答

2

後臺線程只能活,只要調用它是活着的線程。由於Web服務器的請求/響應生命週期有限,因此您的後臺進程不能超過此時間限制。一旦在Web服務器上達到超時,服務器將生成響應(超時),將其推送到客戶端並停止線程。這個事件會殺死你的後臺線程,所以如果它在數據庫中更新,它就會停止。如果您正在寫文件,它會將該文件打開,鎖定並寫入不正確(需要重新啓動才能重新獲得對損壞文件的訪問)。

+0

那麼你認爲這個解決方案是什麼? – meetpd 2011-02-05 02:49:23