asynchronous programming question

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
 
C

Codemonkey

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

100

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top