NegotiateStream.EndRead(IAsyncResult) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
結束藉由呼叫 BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) 啟動的非同步讀取作業。
public:
override int EndRead(IAsyncResult ^ asyncResult);
public override int EndRead (IAsyncResult asyncResult);
override this.EndRead : IAsyncResult -> int
Public Overrides Function EndRead (asyncResult As IAsyncResult) As Integer
參數
- asyncResult
- IAsyncResult
IAsyncResult 執行個體,由對 BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) 的呼叫所傳回。
傳回
Int32 值,指定從基礎資料流中讀取的位元組數。
例外狀況
asyncResult
為 null
。
AsyncResult 不是由呼叫 BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) 的方式所建立。
讀取作業失敗。
範例
下列程式代碼範例示範結束異步讀取作業。 如需示範啟動作業的範例,請參閱 BeginRead。
static void EndReadCallback( IAsyncResult^ ar )
{
// Get the saved data.
ClientState^ cState = dynamic_cast<ClientState^>(ar->AsyncState);
TcpClient^ clientRequest = cState->Client;
NegotiateStream^ authStream = dynamic_cast<NegotiateStream^>(cState->AuthStream);
// Get the buffer that stores the message sent by the client.
int bytes = -1;
// Read the client message.
try
{
bytes = authStream->EndRead( ar );
cState->Message->Append( Encoding::UTF8->GetChars( cState->Buffer, 0, bytes ) );
if ( bytes != 0 )
{
authStream->BeginRead( cState->Buffer, 0, cState->Buffer->Length, gcnew AsyncCallback( EndReadCallback ), cState );
return;
}
}
catch ( Exception^ e )
{
// A real application should do something
// useful here, such as logging the failure.
Console::WriteLine( L"Client message exception:" );
Console::WriteLine( e );
cState->Waiter->Set();
return;
}
IIdentity^ id = authStream->RemoteIdentity;
Console::WriteLine( L"{0} says {1}", id->Name, cState->Message );
cState->Waiter->Set();
}
private static void EndReadCallback(ClientState cState, int bytes)
{
NegotiateStream authStream = (NegotiateStream)cState.AuthenticatedStream;
// Read the client message.
try
{
cState.Message.Append(Encoding.UTF8.GetChars(cState.Buffer, 0, bytes));
if (bytes != 0)
{
Task<int> readTask = authStream.ReadAsync(cState.Buffer, 0, cState.Buffer.Length);
readTask
.ContinueWith(task => { EndReadCallback(cState, task.Result); })
.Wait();
return;
}
}
catch (Exception e)
{
// A real application should do something
// useful here, such as logging the failure.
Console.WriteLine("Client message exception:");
Console.WriteLine(e);
return;
}
IIdentity id = authStream.RemoteIdentity;
Console.WriteLine("{0} says {1}", id.Name, cState.Message.ToString());
}
備註
如果作業尚未完成,這個方法會封鎖直到它完成為止。
若要同步執行這項作業,請使用 Read 方法。
在成功驗證之前,您無法呼叫此方法。 若要進行驗證,請呼叫其中一個 AuthenticateAsClient、 AuthenticateAsClientAsync、 BeginAuthenticateAsClient、 AuthenticateAsServer、 AuthenticateAsServerAsync或 BeginAuthenticateAsServer 方法。