多线程文件写入多线程、文件

2023-09-03 00:39:11 作者:等,一个漫长的。

我想写不同部分使用多线程一个大的文件,就像一个分段的文件下载会做。

I am trying to write to different pieces of a large file using multiple threads, just like a segmented file downloader would do.

我的问题是,什么是安全的方式做到这一点?难道我打开写文件,创建我的线程,传递Stream对象每个线程?我不希望发生的错误,因为有多个线程在潜在地同时访问同一对象

My question is, what is the safe way to do this? Do I open the file for writing, create my threads, passing the Stream object to each thread? I don't want an error to occur because multiple threads are accessing the same object at potentially the same time.

这是C#的方式。

推荐答案

我个人建议你的读取的在多线程数据,但实际上的写的把它从单个线程。这很可能是相当简单的方式。你可以使用一个生产者/消费者队列(这是的真正的容易.NET 4中),然后每个生产商将饲料对指标数据。那么消费者线程可能只是顺序寻找,写,寻求,写等。

I would personally suggest that you fetch the data in multiple threads, but actually write to it from a single thread. It's likely to be considerably simpler that way. You could use a producer/consumer queue (which is really easy in .NET 4) and then each producer would feed pairs of "index, data". The consumer thread could then just sequentially seek, write, seek, write etc.