473,796 Members | 2,640 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

asynchronous programming question

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(B yVal sender ...) Handles CallBtn.Click

webServiceObj = New MyDatabaseWSCla ss()|
Dim delCB As New AsyncCallback(A ddressOf MyCallBack)
aResult = webServiceObj.B eginConnectToDB (CInt(txtSecond s.Text), delCB,
Now)

End Sub

Private Sub UpdateUI()
OutputLabel.Tex t = "Async: Web service call complete."
End If

Private Sub MyCallBack(ByVa l result As IAsyncResult)
If webServiceObj.E ndConnectToDB(r esult) = True Then
DisplayMessage( result)
End If

' following is NOT allowed although it works fine ?????
OutputLabel.Tex t = "Async: Web service call complete."
Dim mi As New MethodInvoker(A ddressOf Me.UpdateUI)
Me.BeginInvoke( mi)
End Sub

Any ideas ?

Thank you

Chris
Nov 15 '05 #1
4 1567
Hi Christian,

When you receive an asynchronous callback, it is recommended
that you always update the control from the same thread in which
the control was created because windows forms controls are _not_ threadsafe.

Typically, if you are updating controls from asynchronous callback methods
that are not executing in the same thread in which the control was created,
use Control.Invoke( ) passing the delegate that updates the control.

You can aso use Control.InvokeR equired to check if the thread is
the same thread in which your control was created, and then accordingly
decide whether you need to call Control.Invoke( ).

Some C# code shown below (same semantics apply to VB.NET):

if( ! MyControl.Invok eRequired)
{
this.AddItemToC ontrol(item);
else
{
MyControl.Invok e(new AddItemDelegate (this.AddItemTo Control, new Object[]
{item}));
}

Regards,
Aravind C
"Chris" <ch********@pan dora.be> wrote in message
news:ci******** ***********@pho bos.telenet-ops.be...
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(B yVal sender ...) Handles CallBtn.Click

webServiceObj = New MyDatabaseWSCla ss()|
Dim delCB As New AsyncCallback(A ddressOf MyCallBack)
aResult = webServiceObj.B eginConnectToDB (CInt(txtSecond s.Text), delCB,
Now)

End Sub

Private Sub UpdateUI()
OutputLabel.Tex t = "Async: Web service call complete."
End If

Private Sub MyCallBack(ByVa l result As IAsyncResult)
If webServiceObj.E ndConnectToDB(r esult) = True Then
DisplayMessage( result)
End If

' following is NOT allowed although it works fine ?????
OutputLabel.Tex t = "Async: Web service call complete."
Dim mi As New MethodInvoker(A ddressOf Me.UpdateUI)
Me.BeginInvoke( mi)
End Sub

Any ideas ?

Thank you

Chris

Nov 15 '05 #2
Chris <ch********@pan dora.be> wrote:
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 ?


Only the UI thread should update the UI - keeping the UI single-
threaded itself makes it much simpler (you don't get two events
occurring at the same time, or two threads trying to update the same
control, etc). The Invoke/BeginInvoke methods make executing the update
on the UI thread simple.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #3
If the question is "Why did the designers not make controls thread safe",
one can only speculate:

In order to make controls thread safe there would have to be locking and
unlocking on all code that made use of the controls. This would make the UI
code in the Framework much more complicated and possibly less efficient.
More importantly, the users would have to worry about deadlocks in the code
they write. This has the potential to stall the UI and might be very
difficult to debug and/or to write correct user code.

IMHO it is much easier to follow the discipline of using Invoke than it
would be to understand the cause and cures of various deadlock problems
among the many UI controls being accessed by multiple threads.

But one can only speculate......

"Chris" <ch********@pan dora.be> wrote in message
news:ci******** ***********@pho bos.telenet-ops.be...
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(B yVal sender ...) Handles CallBtn.Click

webServiceObj = New MyDatabaseWSCla ss()|
Dim delCB As New AsyncCallback(A ddressOf MyCallBack)
aResult = webServiceObj.B eginConnectToDB (CInt(txtSecond s.Text), delCB,
Now)

End Sub

Private Sub UpdateUI()
OutputLabel.Tex t = "Async: Web service call complete."
End If

Private Sub MyCallBack(ByVa l result As IAsyncResult)
If webServiceObj.E ndConnectToDB(r esult) = True Then
DisplayMessage( result)
End If

' following is NOT allowed although it works fine ?????
OutputLabel.Tex t = "Async: Web service call complete."
Dim mi As New MethodInvoker(A ddressOf Me.UpdateUI)
Me.BeginInvoke( mi)
End Sub

Any ideas ?

Thank you

Chris

Nov 15 '05 #4
Fred Mellender wrote:
If the question is "Why did the designers not make controls thread
safe", one can only speculate:


The reason is that windows messages queues are thread based. Unless .NET is
changed to do away with the dependence on windows messages for UI code,
you'll always have this issue. Avalon in Longhorn is supposed to get rid of
this dependence on thread-based message queues, but I haven't done enough
tests to verify this.

Richard
--
my email ev******@zicf.b et is encrypted with ROT13 (www.rot13.org)
Nov 15 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3486
by: ... | last post by:
Does anyone know a good tutorial on asynchronous programming in .net AsyncCallback And IASyncResult are driving me crazy. And the msdn documentation is not really helpful on this topic I appreciate any recommendation.
5
5647
by: a.kostrzewa | last post by:
I have a question about C#. How can I stop asynchronous read/write operation ( BeginReceive() / BeginSend() ) if timeout occurs? The Socket class doesn't make any cancel method available. I used CancelIo(HANDLE hFile) method (declared in Winbase.h) in C++. Thanks for help. Olek
5
2094
by: Daniel J Rodriguez | last post by:
Greetings everyone! This is a fairly broard question.. But should be enough to suffice for an answer. Currently we are making an entreprise database server. We will be using C# - my question is this - is Asynchronous Programming in C# sufficient for production grade quality? If so - does anyone know where to find out how many concurrent connections can be reached (although dependant on their data transfered)? Any information in...
9
8676
by: Michael Lindsey | last post by:
I need to write a server app to send images to client GUIs that are outside of the server's domain. The client will have the file system path to the image but can not access the file system. I am trying to decide if I should use remoting vs. writing a server that uses networkstreams. I have read that networkstreams\tcp programming should be faster than remoting and is a better choice for what I am doing but that it is difficult to code.
4
348
by: bernardpace | last post by:
Hi, I am trying to get more familiar with asynchronous programming. I was reading through the document found on the page: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpovrasynchronousprogrammingoverview.asp Now, I read that 'Always call EndInvoke after your asynchronous call completes'.
2
1377
by: Chris | last post by:
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 :
1
1556
by: Julian Hershel | last post by:
Reading about asynchronous programming (ms-help://MS.NETFrameworkSDK/cpguidenf/html/cpconasynchronousdesignpatterno verview.htm) I could not clarify some doubts. Hope you can help me. 1) Are asynchronous programming and multithreaded programming two different pictures? As I read the help topic above it is not clear to me if the design pattern opens a new thread or not to run the methods asynchronously. 2) One unique thread can run...
1
3175
by: org | last post by:
Hi, I'm developing a web service with should be used by an .NET CF2 client and an .NET 2.0 Windows client. I've tried to put all the connection logic into one class, which could be used in common from the mobile and the windows client. But this didn't work: The new .NET framework supports asynchronous web services with the "MethodnameCompleted+=new MethodNameEventHandler pattern, but the "old style" .NET 1 pattern used in the compact...
3
2098
by: =?Utf-8?B?bWs=?= | last post by:
Hi everyone, I need to refactor some of our processes using the asynchronous programming model. I have defined a couple of arrays of delegates to pipline the asynchronous invocations through different stages of execution. However I was wondering if there was any information available regarding the limitations of the asynchronous model, in particular maximum numbers of asynchronous elements, and limitations of multiple requests potentially...
0
9673
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9525
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10452
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10221
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10169
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6785
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5569
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4115
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2924
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.