"Controls in Windows Forms are bound to a specific thread and are not
thread safe. Therefore, if you are calling a control's method from a
different thread, you must use one of the control's invoke methods to
marshal the call to the proper thread. This property can be used to
determine if you must call an invoke method, which can be useful if you
do not know what thread owns a control. There are four methods on a
control that are safe to call from any thread: Invoke, BeginInvoke,
EndInvoke and CreateGraphics. For all other method calls, you should use
one of these invoke methods when calling from a different thread."
******
instead of
OutputLabel.Text = "Async: Web service call complete."
use
OutputLabel.Invoke(New UpdateLabelDelegate(AddressOf LabelUpdate), New
Object() {OutputLabel})
******
Declare the following:
Delegate Sub UpdateLabelDelegate(ByVal lbl As Label)
******
and add the following sub:
Private Sub UpdateLabel(ByVal lbl As Label)
OutputLabel.Text = "Async: Web service call complete."
End Sub
*************
Chris wrote:
Hello,
With asynchronous programming :
Why does the callback-function (running in a worker thread) may not update
the state of a control on the main-form ?
The docs say that you must use a MethodInvoker instead as in following
example :
Private Sub CallBtn_Click(ByVal sender ...) Handles CallBtn.Click
webServiceObj = New MyDatabaseWSClass()|
Dim delCB As New AsyncCallback(AddressOf MyCallBack)
aResult = webServiceObj.BeginConnectToDB(CInt(txtSeconds.Tex t), delCB,
Now)
End Sub
Private Sub UpdateUI()
OutputLabel.Text = "Async: Web service call complete."
End If
Private Sub MyCallBack(ByVal result As IAsyncResult)
If webServiceObj.EndConnectToDB(result) = True Then
DisplayMessage(result)
End If
' following is NOT allowed although it works fine ?????
OutputLabel.Text = "Async: Web service call complete."
Dim mi As New MethodInvoker(AddressOf Me.UpdateUI)
Me.BeginInvoke(mi)
End Sub
Any ideas ?
Thank you
Chris