2011-09-03 114 views
0

我有一个循环(BackgroundWorker的),这种情况正在改变一个图片的位置非常频繁,但我发现了一个错误 -VB.NET跨线程操作无效

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) 
+3

[主UI窗口未更新控件 - 跨线程操作无效]的可能重复(http://stackoverflow.com/questions/470390/main-ui-windows-not-updating-control-cross -thread操作 - 不有效) –

回答

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 
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