2011-09-03 115 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