我有一个网页,它由一个用于数据输入的表单和一个用于显示结果的面板组成。此页面是用 VB.Net 编写的,托管它的网站是 ASP.Net。
页面的正常使用情况如下:
- 用户输入带有一些数据/过滤器的表单
- 用户按下“搜索”按钮
- A
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
这是一种正确的做事方式吗?这是更好的做事方式吗?