This documentation is archived and is not being maintained.

UdpClient.BeginReceive Method

Note: This method is new in the .NET Framework version 2.0.

Receives a datagram from a remote host asynchronously.

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

public IAsyncResult BeginReceive (
	AsyncCallback requestCallback,
	Object state
)
public IAsyncResult BeginReceive (
	AsyncCallback requestCallback, 
	Object state
)
public function BeginReceive (
	requestCallback : AsyncCallback, 
	state : Object
) : IAsyncResult

Parameters

requestCallback

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

state

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

Return Value

An IAsyncResult object that references the asynchronous receive.

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

This method does not block until the operation is complete. To block until the operation is complete, use the Receive method.

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

The following code example uses BeginReceive to asynchronously receive a server response.

public static bool messageReceived = false;

public static void ReceiveCallback(IAsyncResult ar)
{
  UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
  IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;

  Byte[] receiveBytes = u.EndReceive(ar, ref e);
  string receiveString = Encoding.ASCII.GetString(receiveBytes);

  Console.WriteLine("Received: {0}", receiveString);
  messageReceived = true;
}

public static void ReceiveMessages()
{
  // Receive a message and write it to the console.
  IPEndPoint e = new IPEndPoint(IPAddress.Any, listenPort);
  UdpClient u = new UdpClient(e);

  UdpState s = new UdpState();
  s.e = e;
  s.u = u;

  Console.WriteLine("listening for messages");
  u.BeginReceive(new AsyncCallback(ReceiveCallback), s);

  // Do some work while we wait for a message. For this example,
  // we'll just sleep
  while (!messageReceived)
  {
    Thread.Sleep(100);
  }
}

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0
Show: