我有一個網頁,它由一個數據輸入窗體和一個顯示結果的面板組成。這個頁面是用VB.Net編寫的,託管它的網站是用ASP.Net編寫的。BackgroundWorker - 等待它完成或超時已過
頁面的正常使用如下:
- 用戶輸入的形式與一些數據/過濾器
- 用戶按下按鈕「搜索」
- 甲
BackgroundWorker
開始尋找解決方案
BackgroundWorker實例存儲在一個靜態變量中,因爲我不關心多用戶場景,但是我並不關心這個選擇,我可以改變它。此外,搜索過程是異步的,但我真的不需要在處理過程中顯示任何內容。 BackgroundWorker將結果存儲在SolutionStorage
對象中。
我的目標如下。
當BackgroundWorker結束時,找到的解決方案必須顯示在頁面上。但是,如果經過一段固定的時間(當前爲三分鐘),它仍然在運行,我想終止它並在那一刻顯示SolutionStorage中存在的解決方案。
代碼如下。
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsNothing(worker) Then
worker.CancelAsync()
End If
worker = New BackgroundWorker()
worker.WorkerReportsProgress = False
worker.WorkerSupportsCancellation = True
AddHandler worker.DoWork, AddressOf workerDo
AddHandler worker.RunWorkerCompleted, AddressOf workerComplete
End Sub
Protected Sub search(ByVal sender As Object, ByVal e As EventArgs) Handles submitButton.Click
worker.RunWorkerAsync()
Thread.Sleep(180 * 1000)
If worker.IsBusy Then
worker.CancelAsync()
Dim solutions = repository.getSolutions()
'' Display solutions
If (solutions.Count > 0) Then
SolutionsRepeater.DataBind()
End If
End If
End Sub
Protected Sub workerDo()
' Collect data from the form
' Build the SolutionStorage
' Start the search
End Sub
Protected Sub workerComplete(sender As Object, e As RunWorkerCompletedEventArgs)
'' Display solutions
If (solutions.Count > 0) Then
SolutionsRepeater.DataBind()
End If
End sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsNothing(worker) Then
worker.CancelAsync()
End If
worker = New BackgroundWorker()
worker.WorkerReportsProgress = False
worker.WorkerSupportsCancellation = True
AddHandler worker.DoWork, AddressOf workerDo
AddHandler worker.RunWorkerCompleted, AddressOf workerComplete
End Sub
這是做事情的正確方法?這是更好的做事方式嗎?
這裏主要的問題是:生成的線程_won't stop_!按照我的意願,該頁面顯示超時時間過後解決方案。但爲什麼線程繼續? 我很關心多用戶場景。全世界有20個人每天訪問該頁面30次。 – Che 2012-09-14 23:07:23