UdpClient.BeginReceive(AsyncCallback, Object) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
非同步接收來自遠端主機的資料報。
public:
IAsyncResult ^ BeginReceive(AsyncCallback ^ requestCallback, System::Object ^ state);
public IAsyncResult BeginReceive(AsyncCallback? requestCallback, object? state);
public IAsyncResult BeginReceive(AsyncCallback requestCallback, object state);
member this.BeginReceive : AsyncCallback * obj -> IAsyncResult
Public Function BeginReceive (requestCallback As AsyncCallback, state As Object) As IAsyncResult
參數
- requestCallback
- AsyncCallback
一個 AsyncCallback 代理,當操作完成時會參考呼叫的方法。
- state
- Object
一個由使用者定義的物件,包含接收操作的資訊。 當操作完成時,這個物件會傳給 requestCallback 代理。
傳回
一個 IAsyncResult 參考非同步接收的物件。
範例
以下程式碼範例用於 BeginReceive 非同步接收伺服器回應。
public struct UdpState
{
public UdpClient u;
public IPEndPoint e;
}
public static bool messageReceived = false;
public static void ReceiveCallback(IAsyncResult ar)
{
UdpClient u = ((UdpState)(ar.AsyncState)).u;
IPEndPoint e = ((UdpState)(ar.AsyncState)).e;
byte[] receiveBytes = u.EndReceive(ar, ref e);
string receiveString = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine($"Received: {receiveString}");
messageReceived = true;
}
public static void ReceiveMessages()
{
// Receive a message and write it to the console.
IPEndPoint e = new IPEndPoint(IPAddress.Any, s_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);
}
}
備註
非同步 BeginReceive 操作必須透過呼叫該 EndReceive 方法來完成。 通常,該方法由 requestCallback 委託人執行。
此方法在操作完成前不會阻塞。 要阻擋直到操作完成,請使用該 Receive 方法。
關於使用非同步程式設計模型的詳細資訊,請參見 「非同步呼叫同步方法」。