从同一个文件中读取多个线程 [英] Multiple Threads reading from the same file

查看:25
本文介绍了从同一个文件中读取多个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要多次读取的 xml 文件.我正在尝试使用 Parallel.ForEach 来加速这个过程,因为读入的数据都与读入的顺序无关.数据只是用于填充对象.我的问题是,即使我每次在线程中以只读方式打开文件,它也会抱怨它被另一个程序打开.(我没有在文本编辑器或任何东西中打开它:))

I have a xml file that needs to be read from many many times. I am trying to use the Parallel.ForEach to speed this processes up since none of that data being read in is relevant as to what order it is being read in. The data is just being used to populate objects. My problem is even though I am opening the file each time in the thread as read only it complains that it is open by another program. (I don't have it opened in a text editor or anything :))

如何实现对同一个文件的多次读取?

How can I accomplish multi reads from the same file?

该文件大约为 18KB,非常小.它被读取了大约 1,800 次.

The file is ~18KB pretty small. It is read from about 1,800 times.

谢谢

推荐答案

如果要多个线程读取同一个文件,需要指定FileShare.Read:

If you want multiple threads to read from the same file, you need to specify FileShare.Read:

using (var stream = File.Open("theFile.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
{
    ...
}

但是,由于多种原因,您不会因此而获得任何加速:

However, you will not achieve any speedup from this, for multiple reasons:

  1. 您的硬盘一次只能读取一件事.尽管您有多个线程同时运行,但这些线程最终都会相互等待.
  2. 您无法轻松解析 XML 文件的一部分.您通常每次都必须解析整个 XML 文件.由于您有多个线程一直在读取它,因此您似乎不希望文件发生更改.既然如此,那为什么还要多读几遍?

这篇关于从同一个文件中读取多个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆