VB.NET跨线程操作无效

时间:2011-09-03 23:55:06

标签: vb.net

我有一个循环(BackgroundWorker),它经常更改PictureBox的位置,但我收到错误 -

Cross-thread operation not valid: Control 'box1' accessed from a thread other than the
  thread it was created on.

我根本不明白,所以我希望有人能帮助我解决这个问题。

代码:

  box1.Location = New Point(posx, posy)

2 个答案:

答案 0 :(得分:2)

当您尝试从创建它的线程以外的线程访问控件时,抛出此异常。

要实现此目的,您需要使用控件的InvokeRequired属性来查看是否需要更新它并更新您需要使用委托的控件。我认为您需要在backgroundWorker_DoWork方法中执行此操作

Private Delegate Sub UpdatePictureBoxDelegate(Point p)

Dim del As New UpdatePictureBoxDelegate(AddressOf UpdatePictureBox)

Private Sub UpdatePictureBox(Point p)
    If pictureBoxVariable.InvokeRequired Then

        Dim del As New UpdatePictureBoxDelegate(AddressOf UpdatePictureBox)
        pictureBoxVariable.Invoke(del, New Object() {p})
    Else
        ' this is UI thread     
    End If
End Sub

答案 1 :(得分:0)

对于遇到此错误的其他人:

尝试调度程序对象:MSDN

我的代码:

Private _dispatcher As Dispatcher

Private Sub ThisAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup
    _dispatcher = Dispatcher.CurrentDispatcher
End Sub

Private Sub otherFunction()
    ' Place where you want to make the cross thread call
   _dispatcher.BeginInvoke(Sub() ThreadSafe())
End Sub

Private Sub ThreadSafe()
    ' here you can make the required calls
End Sub