我需要在同一文件的不同位置批量写入数据。我希望以最佳性能实现此操作,因此已查看了同步的FileStream.Write和异步的FileStream.BeginWrite方法。
同步的实现很简单,只需在循环中调用所需次数的FileStream.Write即可。异步版本在循环中调用FileStream.BeginWrite,然后执行WaitHandle.WaitAll以阻止,直到它们全部完成。令人惊讶的是,这比简单的同步版本运行得更慢。
我已使用正确的构造函数创建了FileStream,因此可以请求异步操作,并且还测试了IAsyncResult.CompletedSynchronous属性,结果为False,因此它们确实以异步方式运行。除了不阻塞线程进行写操作之外,使用异步版本还有什么意义吗?
以下是我用于测试异步方法的代码,也许有明显的错误?
同步的实现很简单,只需在循环中调用所需次数的FileStream.Write即可。异步版本在循环中调用FileStream.BeginWrite,然后执行WaitHandle.WaitAll以阻止,直到它们全部完成。令人惊讶的是,这比简单的同步版本运行得更慢。
我已使用正确的构造函数创建了FileStream,因此可以请求异步操作,并且还测试了IAsyncResult.CompletedSynchronous属性,结果为False,因此它们确实以异步方式运行。除了不阻塞线程进行写操作之外,使用异步版本还有什么意义吗?
以下是我用于测试异步方法的代码,也许有明显的错误?
// 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();