【发布时间】:2011-10-11 23:15:03
【问题描述】:
我需要在文件中的不同位置对同一个文件进行一批写入。我想以可能的最佳性能实现这一目标,因此查看了同步 FileStream.Write 和异步 FileStream.BeginWrite 方法。
同步实现很简单,只需在循环中调用 FileStream.Write 所需的次数。异步版本在循环中调用 FileStream.BeginWrite,然后执行 WaitHandle.WaitAll 以阻塞直到它们全部完成。令我惊讶的是,这比简单的同步版本要慢。
我使用正确的构造函数创建了 FileStream,因此我可以请求异步操作,并且我还测试了指示 False 的 IAsyncResult.CompletedSynchronous 属性,因此它们确实以异步方式操作。似乎使用 BeginWrite 的唯一好处是在写入发生时您不会阻塞线程。除了这个好处之外,使用异步版本还有什么意义吗?
这是我用来玩异步方法的测试代码,可能有明显的错误?
// Size of a chunk to be written to file
var chunk = 1024 * 64;
// Number of chunks to write async
var reps = 32;
// Create new file and set length
var fs = new FileStream(@"C:\testfile.dat",
FileMode.Create, FileAccess.ReadWrite,
FileShare.None, chunk, true);
fs.SetLength(chunk * reps);
// Allocate resources
byte[] bytes = new byte[chunk];
WaitHandle[] handles = new WaitHandle[reps];
for (int i = 0; i < reps; i++)
{
fs.Seek(chunk * i, SeekOrigin.Begin);
handles[i] = fs.BeginWrite(bytes, 0, chunk, null, null).AsyncWaitHandle;
}
// Wait for all async operations to complete
WaitHandle.WaitAll(handles);
fs.Flush();
fs.Close();
【问题讨论】:
-
您是否有任何特殊原因必须进行多次 BeginWrite 调用?
-
我的实际代码需要写入文件的不同部分,因此实际上每个部分都会寻找不同的位置然后写入。
标签: c# .net asynchronous filestream