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 可以在每个 IAsyncResult 位置 BeginRead调用 。 调用 EndRead 指示从流中读取的字节数。 EndRead 将在 I/O 操作完成之前阻止。