hello fellow programmers, i was just having some problems on how to make an asynchronous call. well, can someone show me a very simple program thats uses asynchronous calls thanks in advance!
hello fellow programmers, i was just having some problems on how to make an asynchronous call. well, can someone show me a very simple program thats uses asynchronous calls thanks in advance!
Asynchronous Calls
Tryin2Bgood
ReneeC
Sorry that I thought you was from Microsoft. Sometimes you are on the top10 list of repliers and I took it for granted that nobody could afford to spend so much time on this forum unless they are paid to do it.
The reason for the many links to our homepage is that it contains a knowledgebase - primary containing subjects about fieldbus systems. This knowledgebase also contain a simple program for serial port communication using VB.NET, so every time somebody has problems with this, it is natural to provide the links. I have always used a direct link to this program - never a general link to our homepage or even to the knowledgebase! I know that the program has been a very great help to many people - from students to professionals. Unlike many of the examples from the VB help files, it is a complete workable solution with a detailed and easy to understand documentation.
Don't complain about something (a link) until you have tried it.
Jassim Rahma
i think i have figured it out myself. heres a very short example.
i contains 2 classes and a delegate sub
here's the source code:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim demo As New AsyncDemo
Dim dasync As New AsyncDelegate(AddressOf demo.AsyncMethod)
Dim result As IAsyncResult = dasync.BeginInvoke(CInt(TextBox1.Text), Nothing, Nothing)
End Sub
End Class
Public Class AsyncDemo
Public Sub AsyncMethod(ByVal intCount As Integer)
Dim x As Integer = 0
For x = 0 To intCount
Console.WriteLine(x)
Next
End Sub
End Class
Public Delegate Sub AsyncDelegate(ByVal intCount As Integer)
so here it is.
powerteh
what exactly is the async you are talking of ReneeC i have been browsing the MSDN library so i just took an example of async then thats it. but my solution is also async right
MikeDai
JerberSoft
Do you mean how to use BeginInvoke BeginInvoke is used to execute a method asynchronous on a specified thread. Its starts the method and then returns immediately before the method has finished the job, so that the method and the routine, from which BeginInvoke is called, runs asynchronous.
In the knowledgebase on our homepage you may find a small program for serial port communication including source code and documentation, which shows how this works and describes the use of BeginInvoke and delegates in details. In this program one routine receives data from a serial port and pass these on to a display routine, which shows the data. The URL is:
http://www.innovatic.dk/knowledg/SerialCOM/SerialCOM.htm
Innovatic, Carsten Kanstrup
PWStevens
I'm not From Microsoft and yes, I'm a former Digital Engineer and I really miss the rich asynch capabilities of VMS. I have no Microsoft stock or any stock at all. I haven't read your page and have no knowledge of any Microsoft crtique. In a very real way, you could me call me rather impartial.
That being said, I've seen repeated references to your home page and your company name many times and it does look like commercialization.
You do bring up some interesting points. Being from DEC I really do prefer single vendor solutions when I can get them. Yes, I use photoshop for graphics, but other than I'm pretty straight in line with Microsoft which is less than perfect. After one and a half decades at DEC, I have a deep appreciation for software and layered products that play together.
I had to smile when you mentioned paper tapes. My first language was FOCAL with a paper tape absolute loader and the interpreter was loaded via paper tape on a 32 KB (16 KW in those days) PDP-11. A 2.5 MB RKO5 was seen to be a huge and expensive disk. Today I'm in danger when my system disk has less than 500 MB of free space.
olgaF
Let me talk about it conceptually....
Synchronous activity waits on something. A given thread is on hold and is resumed by completion or state conversion on the wait.
Asynch sets up a request and continues processing doing what it needs to do until the thread ends. When the request is completed a second method is executed. In the mean while the process has been resposive because able to respond to events. The awakening thread will need to establsh enough "context" to know what it needs to do and where to put data.
Here's the example I was thinking about.....
Public Class HttpWebRequestBeginGetRequest
Public Shared allDone As New System.Threading.ManualResetEvent(False)
Public Sub GetRequest(ByVal URL As String)
' Create a new HttpWebRequest object.
' Dim request As HttpWebRequest = CType(WebRequest.Create("http://www.contoso.com/example.aspx"), _
' HttpWebRequest)
Dim request As HttpWebRequest = CType(WebRequest.Create(URL), HttpWebRequest)
' Set the ContentType property.
request.ContentType = "application/x-www-form-urlencoded"
' Set the Method property to 'POST' to post data to the URI.
request.Method = "POST"
' Start the asynchronous operation.
Dim result As IAsyncResult = _
CType(request.BeginGetRequestStream(AddressOf ReadCallback, request), IAsyncResult)
' Keep the main thread from continuing while the asynchronous
' operation completes. A real world application
' could do something useful such as updating its user interface or issuing other requests..
allDone.WaitOne()
' Get the response.
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
Dim streamResponse As Stream = response.GetResponseStream()
Dim streamRead As New StreamReader(streamResponse)
Dim responseString As String = streamRead.ReadToEnd()
Console.WriteLine(responseString)
' Close Stream object.
streamResponse.Close()
streamRead.Close()
' Release the HttpWebResponse.
response.Close()
End Sub ' Main
Private Sub ReadCallback(ByVal asynchronousResult As IAsyncResult)
Dim request As HttpWebRequest = CType(asynchronousResult.AsyncState, HttpWebRequest)
' End the operation.
Dim postStream As Stream = request.EndGetRequestStream(asynchronousResult)
Dim postData As String = "Hello"
Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("hello")
postStream.Write(byteArray, 0, postData.Length)
postStream.Close()
allDone.Set()
End Sub ' ReadCallback
End Class ' HttpWebRequest_BeginGetRequest
This is, unfortunately a tricky example. This thing sets up the request in blue. The is room for processing in the green. And finally the thread does wait.
The Asynch portion starts with request completion, makes a reply AND resets the wait when it's finished resuming the wait.
There are cleaner and easier to understand examples than this one. The examples I really like are ones where the request is made and there is an END SUB and the process is free. Later there is a routine like ReadCallback. It starts, establishes context and finshes what it needs to do
I was just looking in Help and I see that much of my example was from help but not all of it.
Here is another example from Help:
Imports System Imports System.Net Imports System.IO Imports System.Text Imports System.Threading Imports Microsoft.VisualBasic Public Class RequestState ' This class stores the State of the request. Private BUFFER_SIZE As Integer = 1024 Public requestData As StringBuilder Public BufferRead() As Byte Public request As HttpWebRequest Public response As HttpWebResponse Public streamResponse As Stream Public Sub New() BufferRead = New Byte(BUFFER_SIZE) {} requestData = New StringBuilder("") request = Nothing streamResponse = Nothing End Sub 'New End Class 'RequestState Class HttpWebRequest_BeginGetResponse Public Shared allDone As New ManualResetEvent(False) Private BUFFER_SIZE As Integer = 1024 Private DefaultTimeout As Integer = 2 * 60 * 1000 ' 2 minutes timeout ' Abort the request if the timer fires. Private Shared Sub TimeoutCallback(state As Object, timedOut As Boolean) If timedOut Then Dim request As HttpWebRequest = state If Not (request Is Nothing) Then request.Abort() End If End If End Sub 'TimeoutCallback Shared Sub Main() Try ' Create a HttpWebrequest object to the desired URL. Dim myHttpWebRequest As HttpWebRequest = WebRequest.Create("http://www.contoso.com") ' Create an instance of the RequestState and assign the previous myHttpWebRequest ' object to its request field. Dim myRequestState As New RequestState() myRequestState.request = myHttpWebRequest Dim myResponse As New HttpWebRequest_BeginGetResponse() ' Start the asynchronous request. Dim result As IAsyncResult = CType(myHttpWebRequest.BeginGetResponse(New AsyncCallback(AddressOf RespCallback), myRequestState), IAsyncResult) ' this line implements the timeout, if there is a timeout, the callback fires and the request aborts. ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, New WaitOrTimerCallback(AddressOf TimeoutCallback), myHttpWebRequest, myResponse.DefaultTimeout, True) ' The response came in the allowed time. The work processing will happen in the ' callback function. allDone.WaitOne() ' Release the HttpWebResponse resource. myRequestState.response.Close() Catch e As WebException Console.WriteLine(ControlChars.Lf + "Main Exception raised!") Console.WriteLine(ControlChars.Lf + "Message:{0}", e.Message) Console.WriteLine(ControlChars.Lf + "Status:{0}", e.Status) Console.WriteLine("Press any key to continue..........") Catch e As Exception Console.WriteLine(ControlChars.Lf + "Main Exception raised!") Console.WriteLine("Source :{0} ", e.Source) Console.WriteLine("Message :{0} ", e.Message) Console.WriteLine("Press any key to continue..........") Console.Read() End Try End Sub 'Main Private Shared Sub RespCallback(asynchronousResult As IAsyncResult) Try ' State of request is asynchronous. Dim myRequestState As RequestState = CType(asynchronousResult.AsyncState, RequestState) Dim myHttpWebRequest As HttpWebRequest = myRequestState.request myRequestState.response = CType(myHttpWebRequest.EndGetResponse(asynchronousResult), HttpWebResponse) ' Read the response into a Stream object. Dim responseStream As Stream = myRequestState.response.GetResponseStream() myRequestState.streamResponse = responseStream ' Begin the Reading of the contents of the HTML page and print it to the console. Dim asynchronousInputRead As IAsyncResult = responseStream.BeginRead(myRequestState.BufferRead, 0, 1024, New AsyncCallback(AddressOf ReadCallBack), myRequestState) Return Catch e As WebException Console.WriteLine(ControlChars.Lf + "RespCallback Exception raised!") Console.WriteLine(ControlChars.Lf + "Message:{0}", e.Message) Console.WriteLine(ControlChars.Lf + "Status:{0}", e.Status) End Try allDone.Set() End Sub 'RespCallback Private Shared Sub ReadCallBack(asyncResult As IAsyncResult) Try Dim myRequestState As RequestState = CType(asyncResult.AsyncState, RequestState) Dim responseStream As Stream = myRequestState.streamResponse Dim read As Integer = responseStream.EndRead(asyncResult) ' Read the HTML page and then print it to the console. If read > 0 Then myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.BufferRead, 0, read)) Dim asynchronousResult As IAsyncResult = responseStream.BeginRead(myRequestState.BufferRead, 0, 1024, New AsyncCallback(AddressOf ReadCallBack), myRequestState) Return Else Console.WriteLine(ControlChars.Lf + "The contents of the Html page are : ") If myRequestState.requestData.Length > 1 Then Dim stringContent As String stringContent = myRequestState.requestData.ToString() Console.WriteLine(stringContent) End If Console.WriteLine("Press any key to continue..........") Console.ReadLine() responseStream.Close() End If Catch e As WebException Console.WriteLine(ControlChars.Lf + "ReadCallBack Exception raised!") Console.WriteLine(ControlChars.Lf + "Message:{0}", e.Message) Console.WriteLine(ControlChars.Lf + "Status:{0}", e.Status) End Try allDone.Set() End Sub 'ReadCallBack End Class 'HttpWebRequest_BeginGetResponseVoiceOfExperience
The advertising really isn't needed..................
LittleSettler
I don't really consider delegates to be asynchonous in the sense I'm talking about. Yes, a timer event is asynchonous but what I'm really talking about is asynchronous I/O. Delegates are about multithreading, another aspect of asynch, but they are not true asynch communications.
S Nesbitt
oh well, that was way too long! can you make an example that is very simple. im still a beginner in .NET so i may not be able to get it easily. please make it simple. sorry but im a little "slow learner" LOL.
r3n
i mean, how to call a method asynchronously. =) just any very simple example will do.
ShAdeVampirE
wow! that added me some knowledge on the async method calling. THANKS a LOT!! now that i have some knowledge on this, i'll try to program more of async calls. thanks again!
Brades
Can you be a little more specific Let me see if I have some code examples. Also HttpWebRequest has examples of Asychronous use in the Help Files. I fear my better asynch examples won't be real different from what you find in help.
Many things are asynch like events and timer tick handlers which is also an event. The Documentcompleted event in the WebBrowser is asynch.
Jamie Thomson
ReneeC
Advertising where It is a link to a help file!
JerberSoft asked for a simple program example, which shows how to do asynchronous calls and since we have such a program on our homepage I thought it was natural to provide the link. What do you want me to do This forum does not have a data base for program examples and documentation, so a link to our own domain is the only way I can show an example, which is too big to be "inline" code of an answer. Besides, it is much faster for me just to provide a link than to copy parts of the code and documentation. Unlike you, I do not get paid for helping your customers!
Please ReneeC, lets be honest with each other. The reason why you and other people from Microsoft don't like links to our homepage is that it contains parts, which are very critical to the way Microsoft is doing things, but Microsoft is so big that you - unlike us - choose the way you want to go entirely by yourselves. Microsoft can do anything they like - make new programming languages, change the world standards - anything, so what are you afraid of Remember the very clever words: If you in a discussion gets angry and upset you are no longer fighting for truth, but for yourself!
We are both from the good old days with paper tapes, Digital PDP11, Nova computers, Commodore Amiga and all that stuff, and we both have the same opinion about C as the world standard, so please ReneeC. Go through the vision and programming pages on our home page and tell me where we are wrong and I will change the point immediately!
A further discussion of this of course do not belong to this forum so use our e-mail mail@innovatic.dk instead. It could be nice to have a serious discussion with Microsoft about how to do things in the future, and it could perhaps be a win-win situtation for both parts.
Paul Bates
OK, here is the vital parts of the program an documentation I refered to.
To make an asynchronous call you need three things - a subroutine, which performs the method you want to call asynchronously, a call of the BeginInvoke metod, which starts this subroutine, and a delegate, which points to this subroutine.
What the BeginInvoke method does is to execute a method (some code) asynchronously on its own thread. BeginInvoke has one or two arguments. The first one is the method to execute, and the second one is any argument(s) to transfer. All GUI objects plus the form classes inherit the BeginInvoke method from their common base class System.Windows.Forms.Control, so they all have this method.
Let us say that you want to write something to TextBox1 in another thread, by means of the following display routine.
Private Sub DisplayRoutine(Byval Buffer As String)
TextBox1.Text = Buffer
End Sub
To avoid an illegal cross-thread call, DisplayRoutine must be executed on the same thread as TextBox1. Therefore we use the BeginInvoke method of this TextBox - TextBox1.BeginInvoke. This starts a method on the same thread as TextBox1 and returns immediately, but because the method (DisplayRoutine) is an object of another thread, we must use a delegate to point to this method. A delegate is an objects you can use to call the methods of other objects. It is sometimes described as a type-safe function pointer because it is similar to function pointers used in other programming languages like C.
In the declaration of the delegate it shall be specified whether the method is a function or a subroutine. Because Display is a subroutine, the delegate is declared as "Public Delegate Sub ...". It is also necessary to specify the argument(s) of the method to call. In this case, the method (DisplayRoutine) has only one argument - the string to write. Because BeginInvoke returns immediately, it is necessary to transfer the string by value (ByVal) or else it may be overwritten before it is used. The total definition of the delegate therefore becomes:
Public Delegate Sub (NameOfDelegate(Byval Buffer As String)
We have now declared a general useable delegate that may be used to transfer a string to any subroutine method of another object. We still need to define which method to receive the string. This is done in the BeginInvoke statement where we define a new instance of this delegate and point it to the display routine (AddressOf DisplayRoutine). The whole BeginInvoke statement therefore becomes:
TextBox1.BeginInvoke(New NameOfDelegate(AddressOf DisplayRoutine), StringToWrite)
What the statement does is therefore to invoke (start) the Display routine (DisplayRoutine) on the same thread as TextBox1, transfer the String as input and then return immediately (before the string is displayed). DisplayRoutine is actually event driven, but since it do not ends with a "Handles xxx", it needs an Invoke or BeginInvoke statement to tell when to start and what thread to use. Even though Display is defined in the same class as the GUI objects, it is not automatically executed on the same thread.