CSharp/C# >> asynchronous programming model with BeginRead...EndRead

by Tony Johansson » Tue, 11 May 2010 18:13:33 GMT


Here I have a simple program that is using asynchronous programming.
As you know there are three styles of programming with Asynchronous
Programming Model(APM) to deal with handling the end of the call in an
asynchronous call: wait-until-done, polling and callback.
In this example I use the Rendezvous model Wait-Unit-Done Model.
When using this model(wait-unitl.done) I can't find point to use this when I
still must wait being blocked until the asynchronous call is complete.
So you are blocked until complete when using wait-until-done and you are
blocked if you use the traditional synchronous model to read a file.
Does someone agree with me in this matter ?

static void Main()
byte[] buffer = new byte[1000];
string filename = "test.txt";
FileStream fstrm = new FileStream(filename, FileMode.Open,
FileShare.Read, 1024, FileOptions.Asynchronous);
IAsyncResult result = fstrm.BeginRead(buffer, 0, buffer.Length, null,
int numBytes = fstrm.EndRead(result);


CSharp/C# >> asynchronous programming model with BeginRead...EndRead

by Alberto Poblacion » Tue, 11 May 2010 19:02:31 GMT

Yes, it doesn't make much sense to use asynchronous programming in this
way UNLESS there are other operations that you can fit in between the
BeginRead and EndRead. But if you are not going to do anything between those
two calls, then use a simple synchronous call (Read(...)), so that your code
will be simpler and you won't waste a thread from the ThreadPool.

CSharp/C# >> asynchronous programming model with BeginRead...EndRead

by Tony Johansson » Tue, 11 May 2010 19:19:17 GMT

"Alberto Poblacion" < XXXX@XXXXX.COM > skrev i

If I compare the time it takes to complete this asynchronous call
IAsyncResult result = fstrm.BeginRead(buffer, 0, buffer.Length, null,
int numBytes = fstrm.EndRead(result);

with the normal using the synchronous call.
I mean if it about the same why use asynchoroun(wait-until-done) when I can
use the synchronous call.
I don't gain anything to use the asynchronous (wait-until-done) model.
Do you agree with me ?

I mean asynchronous is good to use if you use the other Rendezvous
medel(polling or callback)


CSharp/C# >> asynchronous programming model with BeginRead...EndRead

by Willem van Rumpt » Tue, 11 May 2010 19:45:46 GMT

Yes, if you know up front that you want the operation to block, then
just use the synchronous calls.

There are scenario's imaginable where blocking may or may not be
required, or where a consumer can optionally pass in his own callback.
In such a case, you can always start out with a BeginXXX, and depending
on the requirement, pass in the callback or issue an EndXXXX on the same
thread. I haven't encountered such scenario's in my own code yet, so
can't say if this would result in cleaner code than (for instance)
explicitely branching between a BeginXXXX - EndXXXX combo and simply
calling XXXX, but it's an option nevertheless.

Also keep in mind that the authors of the documentation were perhaps
more aiming at completeness of describing the valid ways to end an
asynchronous operation than the usefullness of the various ways
Willem van Rumpt

CSharp/C# >> asynchronous programming model with BeginRead...EndRead

by Patrice » Wed, 12 May 2010 19:55:25 GMT

As Alberto explained the goal of this asynchronous pattern is not to make
the BeginRead/EndRead pair quicker.

You can make your application quicker by starting an operation that keeps
running on its own (even if this operation is just waiting for some data to
be available). Meanwhile you do something else and later you read the result
(wether or not it has actually completed, waiting if needed).

I would suggest testing this pattern with web services calls rather than
disk IOs for full control.

You could easily create a sequential app that simulates :
- a call to a web service that takes 5 s
- another call to a web service that takes 5 s
- a local processing that takes 4 s
So this version will take 14 s.

Now if you do :
- a first asynchronous call (0 s)
- a second asynchronous call (0 s)
- the local processing (4 s)
- get the result of previous calls (will likely wait a bit as 5 s is longer
than 4)

It should take around 5 s. Then you can further test by making the local
processing longer than the web services call etc... You have full control
about all the elements on which you test this pattern...

Similar Threads

1. Looking for good c# sample NetworkStream BeginRead/EndRead... - Microsoft .NET Framework

2. NetworkStream / BeginRead / EndRead / Dataavailable: can't understand MSDN code sample


I need to asynchronously read from a network (TCP) stream, and I am
having trouble with retrieving whole blocks; I get a break in the data
block every 1460 bytes which relates to network packet sizes I guess.

To get this fixed, I am trying to follow an example in the MSDN, which
pretty much resembles what I want to do. Since the code (I can't do
this in a static class for example) is not 100% what I need, I
certainly would like to understand what I am doing, but I guess I am
lacking some fundamentals of asynchronous programming since I simply
do not understand the code snippet. Here it is:

public static void myReadCallBack(IAsyncResult ar ){

    NetworkStream myNetworkStream = (NetworkStream)ar.AsyncState;
    byte[] myReadBuffer = new byte[1024];
    String myCompleteMessage = "";
    int numberOfBytesRead;

    numberOfBytesRead = myNetworkStream.EndRead(ar);
    myCompleteMessage = 
Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
    // message received may be larger than buffer size so loop through
until you have it all.
        myNetworkStream.BeginRead(myReadBuffer, 0,


    // Print out the received message to the console.
    Console.WriteLine("You received the following message : " +

I wonder, how myCompleteMessage can ever add up to the complete
message, since it will be reinitialized at every callback, won't it?

If somebody can help me to understand this (what happens
"while(myNetworkStream.DataAvailable){...}") , I would be most

Best regards


3. Callbacks Across AppDomains (Asynchronous Programming Model) - CSharp/C#

4. Asynchronous Programming Model

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 
queuing up to call the same callback, and also any information regarding 
exception management in the apm.  Thanks for any input.

5. more about asynchronous programming Model(APM) - CSharp/C#

6. Asynchronous Programming Model & ADO.NET

7. Asynchronous Programming Model - how to implement? - .NET Windows Forms

8. synchronous vs. asynchronous exception model

Can someone explaing the difference between these exception models regarding 
the structured exception handling?  The documentation is not clear.  Some 
code would actually help.