BackgroundWorker,访问数据库查询的问题
前几天看了个大神的贴子,学习了用BackgroundWorker控件,在Dowork里做花时间长的处理。
正好的我的程序里有个地方,需要查询数据库,且执行这个SQL文需要花费很长的时间大约1分钟吧。为了在查询时不叫画面死掉,所以就用了BackgroundWorker。
代码如下。
- VB.NET code
Private Sub FrmReports_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Me.BackgroundWorker1.WorkerReportsProgress = True Me.BackgroundWorker1.WorkerSupportsCancellation = TrueEnd Sub开始执行 Private Sub startAsyncButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles startAsyncButton.Click If BackgroundWorker1.IsBusy <> True Then BackgroundWorker1.RunWorkerAsync() End If End Sub取消按钮 Private Sub cancelAsyncButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cancelAsyncButton.Click If BackgroundWorker1.WorkerSupportsCancellation = True BackgroundWorker1.CancelAsync() End If End Sub查询 Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork Dim worker As BackgroundWorker = CType(sender, BackgroundWorker) Dim hashSearch As New Hashtable hashSearch.Item("AcceptDateF") = "2012-01-01 00:00:00" hashSearch.Item("AcceptDateT") = "2012-03-01 59:59:59" Dim dbCls As New DbInputData '这句话执行SQL问查询,费时1分钟,这个时候画面死掉了。。 dbRet = dbCls.SearchAcceptDataList(hashSearch, False, 50, 1) End Sub Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged 这啥也没写,本应该在这通过BackgroundWorker1.ReportProgress的方法来执行这个方法的 但是,DoWork中,没有能BackgroundWorker1.ReportProgress的地方了我觉的。。 End Sub完成方法 Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted If e.Cancelled = True Then resultLabel.Text = "Canceled!" ElseIf e.Error IsNot Nothing Then Else resultLabel.Text = "完成 " & dbRet.Count End If End Sub以上就是我的全部代码了。
如果在DoWork里是一个循环的话,我可以在循环里调用BackgroundWorker1.ReportProgress,来唤醒BackgroundWorker1_ProgressChanged方法,激活画面,但是现在我只在DoWork里调了一个SQL文,但SQl文
执行的时间比较长,这样画面有没有反应了。。。
请明白的大神指点,像我这样的需求该咋办。。。怎样在查询是画面不死掉。
[解决办法]
用法没问题啊,我也是这么用的,而且没有问题。
画面不会有问题的,你在查询里面填几个线程延迟看看。让他刷新下界面。
或者看看其他人怎么说吧