BeginSend Method (Byte[], Int32, AsyncCallback, Object)

UdpClient.BeginSend Method (Byte[], Int32, AsyncCallback, Object)


Sends a datagram to a remote host asynchronously. The destination was specified previously by a call to Connect.

Namespace:   System.Net.Sockets
Assembly:  System (in System.dll)

[HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading = true)]
public IAsyncResult BeginSend(
	byte[] datagram,
	int bytes,
	AsyncCallback requestCallback,
	object state


Type: System.Byte[]

A Byte array that contains the data to be sent.

Type: System.Int32

The number of bytes to send.

Type: System.AsyncCallback

An AsyncCallback delegate that references the method to invoke when the operation is complete.

Type: System.Object

A user-defined object that contains information about the send operation. This object is passed to the requestCallback delegate when the operation is complete.

Return Value

Type: System.IAsyncResult

An IAsyncResult object that references the asynchronous send.

The asynchronous BeginSend operation must be completed by calling the EndSend method. Typically, the method is invoked by the requestCallback delegate.

This method does not block until the operation completes. To block until the operation is complete, use one of the Send method overloads.

For detailed information about using the asynchronous programming model, see Calling Synchronous Methods Asynchronously.

The following code example uses BeginSend to asynchronously send a server request.

public static bool messageSent = false;

public static void SendCallback(IAsyncResult ar)
  UdpClient u = (UdpClient)ar.AsyncState;

  Console.WriteLine("number of bytes sent: {0}", u.EndSend(ar));
  messageSent = true;
static void SendMessage1(string server, string message)
  // create the udp socket
  UdpClient u = new UdpClient();

  u.Connect(server, listenPort);
  Byte [] sendBytes = Encoding.ASCII.GetBytes(message);

  // send the message
  // the destination is defined by the call to .Connect()
  u.BeginSend(sendBytes, sendBytes.Length, 
              new AsyncCallback(SendCallback), u);

  // Do some work while we wait for the send to complete. For 
  // this example, we'll just sleep
  while (!messageSent)

.NET Framework
Available since 2.0
Return to top
© 2016 Microsoft