2011-02-04 51 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