将数据写入文件的最有效方法是什么?

时间:2009-04-17 07:02:57

标签: c# winapi file-io

我需要在我的应用程序中写入大量数据。数据定期到达并推入队列。

//producer
queue_.push( new_data );// new_data is a 64kb memory range
PostThreadMessage(worker_thread_id_, MyMsg, 0, 0);//notify the worker thread

之后,我需要将此数据写入文件。我有另一个线程,从队列中获取数据并写入它。

//consumer
while(GetMessage(msg, 0, 0))
{
   data = queue_.pop();
   WriteFile(file_handle_, data.begin(), data.size(), &io_bytes, NULL);
}

这很简单,但效率不高。 另一个机会是使用IO完成端口。

//producer
//file must be associated with io completion port
WriteFile( file_handle_
         , new_data.begin()
         , new_data.size()
         , &io_bytes
         , new my_overlaped(new_data) );
消费者只是删除未使用的缓冲区

my_completion_key* ck = 0;
my_overlapped* op = 0;
DWORD res = GetQueuedIOCompletionStatus(completion_port_, &io_bytes, &ck, &op);
//process errors
delete op->data;

在Windows上执行大量文件i / o操作的首选方法是什么?

1 个答案:

答案 0 :(得分:1)

很难分辨,因为您目前的方法遇到了什么样的问题并不清楚。在专用的“编写器”线程中进行异步不应该导致相当大的性能提升。

如果你有小而频繁的写入(因此频繁的WriteFile成本成为瓶颈)我建议实现一种惰性写入 - 收集数据并在达到某个音量阈值时将其刷新到文件中。