Read large txt file multithreaded?

前端 未结 6 1829
忘了有多久
忘了有多久 2020-11-30 02:17

I have large txt file with 100000 lines. I need to start n-count of threads and give every thread unique line from this file.

What is the best way to do this? I thin

6条回答
  •  天命终不由人
    2020-11-30 02:38

    As @dtb mentioned above, the fastest way to read a file and then process the individual lines in a file is to: 1) do a File.ReadAllLines() into an array 2) Use a Parallel.For loop to iterate over the array.

    You can read more performance benchmarks here.

    The basic gist of the code you would have to write is:

    string[] AllLines = File.ReadAllLines(fileName);
    Parallel.For(0, AllLines.Length, x =>
    {
        DoStuff(AllLines[x]);
        //whatever you need to do
    });
    

    With the introduction of bigger array sizes in .Net4, as long as you have plenty of memory, this shouldn't be an issue.

提交回复
热议问题