- ar
- A IAsyncResult object that holds the state information for the asynchronous operation.
The number of bytes read from the System.Net.Sockets.NetworkStream.
Type Reason ArgumentNullException asyncResult is null. System.IO.IOException Note: This method catches all exceptions thrown by the Socket.EndReceive(IAsyncResult) method.ObjectDisposedException The current instance has been disposed.
The NetworkStream.EndRead(IAsyncResult) method completes the asynchronous read operation started in the NetworkStream.BeginRead(Byte[], int, int, AsyncCallback, object) method.
Before calling NetworkStream.BeginRead(Byte[], int, int, AsyncCallback, object), you need to create a callback method that implements the AsyncCallback delegate. This callback method executes in a separate thread and is called by the system after NetworkStream.BeginRead(Byte[], int, int, AsyncCallback, object) returns. The callback method must accept the IAsyncResult returned from the NetworkStream.BeginRead(Byte[], int, int, AsyncCallback, object) method as a parameter.
Within the callback method, call the IAsyncResult.AsyncState property of the IAsyncResult to obtain the state object passed to the NetworkStream.BeginRead(Byte[], int, int, AsyncCallback, object) method. Extract the receiving System.Net.Sockets.NetworkStream from this state object. After obtaining the System.Net.Sockets.NetworkStream, call the NetworkStream.EndRead(IAsyncResult) method to successfully complete the read operation and return the number of bytes read.
The NetworkStream.EndRead(IAsyncResult) method blocks until data is available. The NetworkStream.EndRead(IAsyncResult) method reads as much data as is available up to the number of bytes specified in the size parameter of the NetworkStream.BeginRead(Byte[], int, int, AsyncCallback, object) method. If the remote host shuts down the System.Net.Sockets.Socket connection and all available data has been received, the NetworkStream.EndRead(IAsyncResult) method completes immediately and returns zero bytes.
To obtain the received data, call the IAsyncResult.AsyncState property of the IAsyncResult, and extract the buffer contained in the resulting state object.
If you receive an System.IO.IOException, check the Exception.InnerException property to determine if it was caused by a System.Net.Sockets.SocketException. If so, use the SocketException.ErrorCode property to obtain the specific error code, and refer to the Windows Sockets version 2 API error code documentation in MSDN for a detailed description of the error.