Multiple Threads reading from the same file

Viewed 37131

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?

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

Thanks

4 Answers

While an old post, it seems to be a popular one so I thought I would add a solution that I have used to good effect for multi-threaded environments that need read access to a file. The file must however be small enough to hold in memory at least for the duration of your processing, and the file must only be read and not written to during the period of shared access.

string FileName = "TextFile.txt";
string[] FileContents = File.ReadAllLines(FileName);

foreach (string strOneLine in FileContents)
{
  // Do work on each line of the file here
}

So long as the file is only being read, multiple threads or programs can access and process it at the same time without treading on one another's toes.

Related