不是因为您使用的是同步Read
方法
如果您希望异步阅读它,则必须使用该BeginRead
方法
下面是一个来自MSDN的 BeginRead 用法示例
private void ReadStreamAsyncImpl(Stream stream)
{
chunk = new byte[chunkSize];
stream.BeginRead(chunk,
0,
chunkSize,
new AsyncCallback(BeginReadCallback),
stream);
}
private void BeginReadCallback(IAsyncResult ar)
{
Stream stream = ar.AsyncState as Stream;
int bytesRead = stream.EndRead(ar);
StreamContentsAsString += StreamEncoding.GetString(chunk, 0, bytesRead);
if (bytesRead < chunkSize) {
// Finished
isOperationInProgress = false;
stream.Close();
if (null != ReadStreamCompleted) {
ReadStreamCompleted(this, new EventArgs());
}
} else {
ReadStreamAsyncImpl(stream);
}
}
也就是说,您可能应该使用 StreamReader 来读取流的字符,而不是自己转换它们。
如果您使用的是 .NET 4.5,您可以使用 ReadAsync 如下(再次来自[MSDN][2]
)
private async void Button_Click(object sender, RoutedEventArgs e) { UnicodeEncoding uniencoding = new UnicodeEncoding(); 字符串文件名 = @"c:\Users\exampleuser\Documents\userinputlog.txt"; 字节[] 结果;
using (FileStream SourceStream = File.Open(filename, FileMode.Open))
{
result = new byte[SourceStream.Length];
await SourceStream.ReadAsync(result, 0, (int)SourceStream.Length);
}
UserInput.Text = uniencoding.GetString(result);
}