0 out of 3 rated this helpful - Rate this topic

NetworkStream.BeginWrite Method

Begins an asynchronous write to a stream.

Namespace:  System.Net.Sockets
Assembly:  System (in System.dll)
[HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading = true)]
public override IAsyncResult BeginWrite(
	byte[] buffer,
	int offset,
	int size,
	AsyncCallback callback,
	Object state
)

Parameters

buffer
Type: System.Byte[]
An array of type Byte that contains the data to write to the NetworkStream.
offset
Type: System.Int32
The location in buffer to begin sending the data.
size
Type: System.Int32
The number of bytes to write to the NetworkStream.
callback
Type: System.AsyncCallback
The AsyncCallback delegate that is executed when BeginWrite completes.
state
Type: System.Object
An object that contains any additional user-defined data.

Return Value

Type: System.IAsyncResult
An IAsyncResult that represents the asynchronous call.
Exception Condition
ArgumentNullException

The buffer parameter is null.

ArgumentOutOfRangeException

The offset parameter is less than 0.

-or-

The offset parameter is greater than the length of buffer.

-or-

The size parameter is less than 0.

-or-

The size parameter is greater than the length of buffer minus the value of the offset parameter.

IOException

The underlying Socket is closed.

-or-

There was a failure while writing to the network.

-or-

An error occurred when accessing the socket. See the Remarks section for more information.

ObjectDisposedException

The NetworkStream is closed.

The BeginWrite method starts an asynchronous send operation to the remote host. Calling the BeginWrite method gives you the ability to send data within a separate execution thread.

You must create a callback method that implements the AsyncCallback delegate and pass its name to the BeginWrite method. At the very minimum, your state parameter must contain the NetworkStream. If your callback needs more information, you can create a small class or structure to hold the NetworkStream and the other required information. Pass the structure or class instance to the BeginWrite method through the state parameter.

Your callback method should implement the EndWrite method. When your application calls BeginWrite, the system uses a separate thread to execute the specified callback method, and blocks on EndWrite until the NetworkStream sends the number of bytes requested or throws an exception. If you want the original thread to block after you call the BeginWrite method, use the WaitOne method. Call Set in the callback method when you want the original thread to continue executing. For additional information about writing callback methods, see Callback Sample.

Note Note

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 in MSDN for a detailed description of the error.

Read and write operations can be performed simultaneously on an instance of the NetworkStream class without the need for synchronization. As long as there is one unique thread for the write operations and one unique thread for the read operations, there will be no cross-interference between read and write threads and no synchronization is required.

Note Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: ExternalThreading. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

The following code example uses BeginWrite to write data asynchronously to a network stream. The myWriteCallBack method implements the AsyncCallback delegate and is called by the system when BeginWrite returns.


//Example of CanWrite, and BeginWrite.

 // Check to see if this NetworkStream is writable.
 if (myNetworkStream.CanWrite){

      byte[] myWriteBuffer = Encoding.ASCII.GetBytes("Are you receiving this message?");
      myNetworkStream.BeginWrite(myWriteBuffer, 0, myWriteBuffer.Length, 
                                                   new AsyncCallback(NetworkStream_ASync_Send_Receive.myWriteCallBack), 
                                                   myNetworkStream);
      allDone.WaitOne();
 }
 else{
      Console.WriteLine("Sorry.  You cannot write to this NetworkStream.");  
 }



.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
The sample is broken
Would be nice to see the callback implementation, as text says "Callback should call EndWrite()". Also the link to "More info on callbacks" somehow refers to native interface. How is this relevant to topic discussed?
AddDone?
What does AllDone refer to here in the example?