asynchronous programming question

  • Thread starter Thread starter Chris
  • Start date Start date
C

Chris

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.Text), 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
 
Chris,

As far as I'm aware, windows forms (which includes all controls) is built
upon the single threaded apartment architecture of parts of the Windows API.
This has the restriction that methods may only be called on the control by
the thread that created the control. Although calling from other threads may
work fine in some cases (like the example you gave), it is unpredictable at
the best of times. This is why you should ensure that you use the Invoke
method on the control to ensure its own thread is used to run the method.

This is a restriction imposed by Windows forms. Most other parts of .net can
be regarded as "free threaded"

Hope this helps,

Trev.
 
Hi,
Actually, this is restriction imposed by Windows OS. More strictly the way
SendMessage API and message queue work. I won't be surprised if there is no
such restriction in Windows Forms part of Compact Framework.

B\rgds
100
 
Back
Top