NetworkStream.EndWrite(IAsyncResult) Method


Handles the end of an asynchronous write.

 override void EndWrite(IAsyncResult ^ asyncResult);
public override void EndWrite (IAsyncResult asyncResult);
override this.EndWrite : IAsyncResult -> unit
Public Overrides Sub EndWrite (asyncResult As IAsyncResult)



The IAsyncResult that represents the asynchronous call.


The asyncResult parameter is null.

The underlying Socket is closed.


An error occurred while writing to the network.


An error occurred when accessing the socket.


In the following code example, myWriteCallback is provided to BeginWrite as the callback method. EndWrite is implemented in myWriteCallback to complete the asynchronous write call started by BeginWrite.

// Example of EndWrite
static void myWriteCallBack( IAsyncResult^ ar )
   NetworkStream^ myNetworkStream = safe_cast<NetworkStream^>(ar->AsyncState);
   myNetworkStream->EndWrite( ar );
// Example of EndWrite
public static void myWriteCallBack(IAsyncResult ar){

     NetworkStream myNetworkStream = (NetworkStream)ar.AsyncState;

' Example of EndWrite
Public Shared Sub myWriteCallBack(ar As IAsyncResult)
   Dim myNetworkStream As NetworkStream = CType(ar.AsyncState, NetworkStream)
End Sub


EndWrite completes the asynchronous send operation started in BeginWrite.

Before calling BeginWrite, 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 BeginWrite returns. The callback method must accept the IAsyncResult returned from the BeginWrite method as a parameter.

Within the callback method, call the AsyncState property of the IAsyncResult parameter to obtain the NetworkStream. After obtaining the NetworkStream, you can call the EndWrite method to successfully complete the send operation and return the number of bytes sent.

The EndWrite method blocks until the requested number of bytes are sent.


If you receive an IOException, check the InnerException property to determine if it was caused by a SocketException. If so, use the ErrorCode property to obtain the specific error code and refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

Applies to

See also