我有一个循环(BackgroundWorker),它非常频繁地更改图片框的位置,但我得到了一个错误-
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)发布于 2011-09-04 08:18:07
当您尝试从创建控制的线程以外的线程访问控制时,将引发此异常。
要解决此问题,您需要使用控件的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发布于 2015-04-13 23:32:09
对于遇到此错误的其他人:
尝试dispatcher对象: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 Subhttps://stackoverflow.com/questions/7296564
复制相似问题