FileStream.EndRead(IAsyncResult) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
等待即將完成的非同步讀取操作。 (考慮改用 ReadAsync(Byte[], Int32, Int32, CancellationToken) 。)
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
指待處理的非同步請求,需等待。
傳回
從串流讀取的位元組數,介於 0 與你請求的位元組數之間。 串流只會在串流結束時回傳 0,否則應該封鎖直到至少有 1 位元組可用。
例外狀況
asyncResult 是 null。
這個 IAsyncResult 物件並非透過呼叫 BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) 這個類別所建立。
串流已關閉或發生內部錯誤。
範例
此程式碼範例是建構子更大範例 FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean) 的一部分。
static void EndReadCallback(IAsyncResult asyncResult)
{
State tempState = (State)asyncResult.AsyncState;
int readCount = tempState.FStream.EndRead(asyncResult);
int i = 0;
while(i < readCount)
{
if(tempState.ReadArray[i] != tempState.WriteArray[i++])
{
Console.WriteLine("Error writing data.");
tempState.FStream.Close();
return;
}
}
Console.WriteLine("The data was written to {0} and verified.",
tempState.FStream.Name);
tempState.FStream.Close();
// Signal the main thread that the verification is finished.
tempState.ManualEvent.Set();
}
let endReadCallback (asyncResult: IAsyncResult) =
let tempState = asyncResult.AsyncState :?> State
let readCount = tempState.FStream.EndRead asyncResult
let mutable i = 0
let mutable errored = false
while i < readCount do
if tempState.ReadArray[i] <> tempState.WriteArray[i] then
printfn "Error writing data."
tempState.FStream.Close()
errored <- true
i <- readCount
i <- i + 1
printfn $"The data was written to {tempState.FStream.Name} and verified."
tempState.FStream.Close()
// Signal the main thread that the verification is finished.
tempState.ManualEvent.Set() |> ignore
Private Shared Sub EndReadCallback(asyncResult As IAsyncResult)
Dim tempState As State = _
DirectCast(asyncResult.AsyncState, State)
Dim readCount As Integer = _
tempState.FStream.EndRead(asyncResult)
Dim i As Integer = 0
While(i < readCount)
If(tempState.ReadArray(i) <> tempState.WriteArray(i))
Console.WriteLine("Error writing data.")
tempState.FStream.Close()
Return
End If
i += 1
End While
Console.WriteLine("The data was written to {0} and " & _
"verified.", tempState.FStream.Name)
tempState.FStream.Close()
' Signal the main thread that the verification is finished.
tempState.ManualEvent.Set()
End Sub
備註
在 .NET Framework 4 及更早版本中,你必須使用像 BeginRead 和 EndRead 這樣的方法來實作非同步檔案操作。 這些方法仍可在 .NET Framework 4.5 中提供,以支援舊有程式碼;然而,新的非同步方法如 ReadAsync、WriteAsync、CopyToAsync 及 FlushAsync,能幫助你更輕鬆地實作非同步檔案操作。
EndRead 必須在每次呼叫 BeginRead時精確地呼叫。 未能在開始下一個讀取前結束讀取程序,可能導致不理想的行為,如死結。
這個方法會覆寫 EndRead。
EndRead 可從 中呼叫 IAsyncResultBeginRead。 呼叫 EndRead 會告訴你從串流讀取了多少位元組。 EndRead 會在 I/O 操作完成前阻塞。