dmg*_*dmg 5 .net c# asynchronous filestream beginread
为什么使用 FileOptions.Asynchronous 创建 FileStream 会导致 FileStream.BeginRead 阻塞调用线程?
这是代码片段:
private static Task<int> ReadFileAsync(string filePath)
{
var file = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite, 64 * 1024, FileOptions.Asynchronous);
FileInfo fi = new FileInfo(filePath);
byte[] buffer = new byte[fi.Length];
Task<int> task = Task<int>.Factory.FromAsync(file.BeginRead, file.EndRead, buffer, 0, buffer.Length, null);
return task.ContinueWith(t =>
{
file.Close();
Console.WriteLine("Done ReadFileAsync, read " + t.Result + " bytes.");
return t.Result;
});
}
Run Code Online (Sandbox Code Playgroud)
当使用 JetBrains dotPeek 深入研究 MSFT FileStream 代码时,他们的代码中似乎存在一个错误:
if (!this._isAsync)
return base.BeginRead(array, offset, numBytes, userCallback, stateObject);
else
return (IAsyncResult) this.BeginReadAsync(array, offset, numBytes, userCallback, stateObject);
Run Code Online (Sandbox Code Playgroud)
BeginRead 方法实际上看起来是通过调度任务来异步读取,但 BeginReadAsync 方法实际上最终会执行同步读取。所以他们的方法命名法是倒退的,调用哪个方法的逻辑是错误的。如果 this._isAsync == true 则应调用 BeginRead。
因此,似乎要让 FileStream.BeginRead 立即返回(异步安排读取),您实际上必须将构造函数中的 useAsync 参数设置为 false。
这是一篇知识库文章,其中列出了可以使您希望异步执行的代码实际同步运行的所有方法。
异步磁盘 I/O 在 Windows NT、Windows 2000 和 Windows XP 上显示为同步
列表中的内容是否适用于您的情况?
您是否尝试过使用 .NET 4.5 的ReadAsync 方法实现相同的行为?
我引用的是MSDN:
在.NET Framework 4及更早版本中,必须使用BeginRead和EndRead等方法来实现异步I/O操作。这些方法在 .NET Framework 4.5 中仍然可用,以支持遗留代码;但是,新的异步方法(例如 ReadAsync、WriteAsync、CopyToAsync 和 FlushAsync)可帮助您更轻松地实现异步 I/O 操作。
编辑 我正在使用 ICH10 和 Windows 7 的 OCZ Vertex 2 上重现您的 256MB 文件问题。我必须生成该文件,重新启动 PC 以清除文件缓存,然后尝试读取相同的文件。
using System;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
string fileName = @"C:\Temp\a1.txt";
int arraySize = 512 * 1024 * 1024;
var bytes = new byte[arraySize];
new Random().NextBytes(bytes);
// This prints false, as expected for async call
var callback = new AsyncCallback(result =>
Console.WriteLine("Completed Synchronously: " + result.CompletedSynchronously));
try
{
// Use this method to generate file...
//WriteFileWithRandomBytes(fileName, arraySize, bytes, callback);
Console.WriteLine("ReadFileAsync invoked at " + DateTimeOffset.Now);
var task = ReadFileAsync(fileName);
Console.WriteLine("ReadFileAsync completed at " + DateTimeOffset.Now);
Task.WaitAll(task);
Console.WriteLine("Wait on a read task completed at " + DateTimeOffset.Now);
}
finally
{
if (File.Exists(fileName))
File.Delete(fileName);
}
}
private static void WriteFileWithRandomBytes(string fileName, int arraySize, byte[] bytes, AsyncCallback callback)
{
using (var fileStream = new FileStream(fileName,
FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 128 * 1024, FileOptions.Asynchronous))
{
Console.WriteLine("BeginWrite invoked at " + DateTimeOffset.Now);
var asyncResult = fileStream.BeginWrite(bytes, 0, arraySize, callback, null);
Console.WriteLine("BeginWrite completed at " + DateTimeOffset.Now);
// completes in 6 seconds or so... Expecting instantaneous return instead of blocking
// I expect runtime to block here...
Task.WaitAll(Task.Factory.FromAsync(asyncResult, fileStream.EndWrite));
// or at least when flushing the stream on the following end-curly
}
}
private static Task<int> ReadFileAsync(string filePath)
{
FileInfo fi = new FileInfo(filePath);
byte[] buffer = new byte[fi.Length];
var file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 64 * 1024, FileOptions.Asynchronous);
Task<int> task = Task<int>.Factory.FromAsync(file.BeginRead, file.EndRead, buffer, 0, buffer.Length, null);
return task.ContinueWith(t =>
{
file.Close();
Console.WriteLine("Done ReadFileAsync, read " + t.Result + " bytes.");
return t.Result;
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
当所有其他方法都失败时,这里是对非托管 API 文档的参考。
| 归档时间: |
|
| 查看次数: |
5023 次 |
| 最近记录: |