VB.NET跨线程操作无效

VB.NET跨线程操作无效,vb.net,Vb.net,我有一个循环(BackgroundWorker),它经常更改PictureBox的位置,但我得到了一个错误- Cross-thread operation not valid: Control 'box1' accessed from a thread other than the thread it was created on. 我一点也不明白,所以我希望有人能帮我解决这个问题 代码: 当您尝试从创建控件的线程以外的线程访问控件时,会引发此异常 要克服此问题,您需要使用控件的invok

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

Cross-thread operation not valid: Control 'box1' accessed from a thread other than the
  thread it was created on.
我一点也不明白,所以我希望有人能帮我解决这个问题

代码:


当您尝试从创建控件的线程以外的线程访问控件时,会引发此异常

要克服此问题,您需要使用控件的
invokererequired
属性来查看是否需要更新它,并且要更新控件,您需要使用委托。我认为你需要在你的后台工作方法中做到这一点

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

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

请尝试dispatcher对象:

我的代码:

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
可能重复的
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