2013年5月20日 星期一

[VB.NET]跨執行緒作業無效-跨執行續操作UI

一,依WindowsForm來說,介面上有二個Button,有一支執行續需要設定這二個Button的Enabled。

如果直接設定會出現跨執行緒作業無效的錯誤訊息。

所以我們可以使用委派來處理跨執行續的問題。

 
Private Delegate Sub MyButtonCallBack(ByVal StartValue As Boolean, ByVal StopValue As Boolean)

Private Sub SetButtonEnabled(ByVal StartValue As Boolean, ByVal StopValue As Boolean)
'判斷是否由執行緒以外的執行緒呼叫,若不是則直接設定Button
If Me.InvokeRequired Then
'實作委派方法
Dim MyButton As New MyButtonCallBack(AddressOf SetButtonEnabled)
'執行委派
Me.Invoke(MyButton, StartValue, StopValue)
Else
Me.btnStart.Enabled = StartValue
Me.btnStop.Enabled = StopValue
End If
End Sub

沒有留言:

張貼留言