BackgroundWorker ProgressChanged事件在新线程中触发,导致无模式形式的跨线程错误

时间:2019-02-28 02:01:41

标签: vb.net multithreading winforms backgroundworker

代码应该是;

  • 查找包含inputStr的字符串的列表
  • 将它们一个一个地添加到ToolStripDropDown列表中,而无需挂起UI

我正在使用BackgroundWorker,并使用以下代码

Protected Overrides Sub OnTextChanged(e As EventArgs)
  Dim bWorker As BackgroundWorker = New BackgroundWorker
  'also tried to declare bWorker in class scope - no change
  AddHandler bWorker.DoWork, AddressOf bw_DoWork
  AddHandler bWorker.ProgressChanged, AddressOf bw_ProgressChanged
  bWorker.WorkerReportsProgress = True
  bWorker.WorkerSupportsCancellation = True
  'Thread is confirmed as 1
  bWorker.RunWorkerAsync(inputStr)
End Sub

Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
  Dim matchList As List(Of String) = getMatchingList(e.Argument) 'Not listed, irrelevant
  'Thread is different, as expected
  For Each lineStr In matchList
    bWorker.ReportProgress(0, lineStr)
  Next
End Sub

Private Sub bw_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
  Dim lblList As Label = New Label With {.Text = e.UserState.ToString}
  Dim hstItem As ToolStripControlHost = New ToolStripControlHost(lblList)
  'Thread is different, unexpected
  toolStripControl.Items.Add(hstItem) 'This line gives me the cross-thread error, since the thread is not 1
End Sub

为了完整起见,此代码位于用户控制代码的后面。该控件在运行时以无模式形式生成(我在创建控件的过程中确认线程号为1)。如果我在表单上调用ShowDialog,以将其显示为模态,则我不会受此问题的困扰,但我需要使表单无模。我尝试在窗体构造函数,Load事件和Shown事件中创建控件,而没有进行任何更改。我还尝试在设计时将backgroundworker添加到用户控件中,再次保持不变。

0 个答案:

没有答案