我正在通过肥皂电话阅读DataTable
,需要很长时间才能完成。为了使GUI保持活动状态并更新选取框,我可以在后台工作程序上执行soapcall并等待它在Runworkercompleted
子中设置全局变量标志。
该表填充得很好,并且dowork返回,但是完成的runworker永远不会被调用。
如果我重新编码这个以将标志设置为DOWORK中的最后一个东西,那么下次我调用TableGetterThread.RunWorkerAsync
它会告诉我它不能同时运行任务
(附加信息:此BackgroundWorker
当前正忙,无法同时运行多个任务。)
对我所做错事的任何帮助都非常感激。
waiting = True
TableGetterThread.RunWorkerAsync(New tableInfo(tablename, filter))
While waiting
Me.Refresh()
Threading.Thread.Sleep(100)
End While
Private Sub TableGetterThread_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles TableGetterThread.DoWork
Dim user As String = "username"
Dim pass As String = "password"
getTable_Table = Nothing
getTable_Table = bromcomReader.getEntityData(e.Argument.tablename, e.Argument.Filter, user, pass).Tables(0)
getTable_Table.TableName = e.Argument.tablename
Console.WriteLine("FinishedDoWork")
End Sub
Private Sub TableGetterThread_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles TableGetterThread.RunWorkerCompleted
Console.WriteLine("Completed")
waiting = False
End Sub
答案 0 :(得分:1)
缺陷在于逻辑本身。主线程和RunWorkerCompleted
必须在同一个线程上运行。因此,当您等待Waiting
设置为false
时,您处于主线程中,因此永远不会调用RunWorkerCompleted
。将waiting = False
设为BackgroundWorker_Dowork
的最后一步。我建议您使用AutoReset Event
代替While loop
等待。
您可以使用此代码作为参考。
Public Class Form1
Private Property waiting As Boolean
Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Console.WriteLine("Hey")
waiting = False
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As System.Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
waiting = True
BackgroundWorker1.RunWorkerAsync()
While waiting
Me.Refresh()
Threading.Thread.Sleep(100)
End While
End Sub
End Class