BufferedStream class - asynchronous read is blocking ?

  • Thread starter Thread starter Niels Johansen
  • Start date Start date
N

Niels Johansen

Hello,

When using the asynchronous read method in the BufferedStream class, [
i.e. BufferedStream.BeginRead() ], it seems to me that it blocks like
the normal synchronous read method. Why is it so? Why does the
BufferedStream.BeginRead() not behave similar to the
NetworkStream.BeginRead() ??

The following short program illustrates my problem.:

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;

class BufferedStreamTest
{
private const int BUFFER_SIZE = 64;
private static byte[] buffer = new byte[BUFFER_SIZE];

[STAThread]
static void Main()
{
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
socket.Bind(new IPEndPoint(IPAddress.Any, 8888));
socket.Listen(10);
socket.BeginAccept(new AsyncCallback(OnAccept), socket);

TcpClient client = new TcpClient();
client.Connect("127.0.0.1", 8888);
// Create a buffered network stream
Stream s = new BufferedStream(client.GetStream());

// Begin the asynchronous read operation
s.BeginRead(buffer, 0, BUFFER_SIZE,
new AsyncCallback(OnRead), s);

Console.WriteLine("Started asynchronous read op..");

/// Just to keep the program running..
Console.ReadLine();
}

public static void OnRead(IAsyncResult result)
{
Stream s = result.AsyncState as Stream;
int bytesRead = s.EndRead(result);
}
public static void OnAccept(IAsyncResult result)
{
Console.WriteLine("Socket connected..");
Socket s = result.AsyncState as Socket;
Socket c = s.EndAccept(result);
}
}


This program blocks when executing the s.BeginRead(..) statement.
However, if I remove the use of the BufferedStream, the s.BeginRead(...)
completes asynchronously..?

Can you please explain to me why this is so ??

thank you,

Niels Johansen
 
Back
Top