简体   繁体   English

使用ParallelForeach处理文件。 这是最好的方法吗?

[英]Processing Files using ParallelForeach. Is this the best approach

Just some advice I have 100.000+ xml file to process and move to another system. 只是一些建议我有100.000+ xml文件来处理和移动到另一个系统。

The concept is pretty simple I have a loop like: 这个概念非常简单我有一个循环:

    public void ProcessFiles()
    {
        IEnumerable<FileInfo> orderedFiles = GetFilesOrdered();

        foreach (FileInfo file in orderedFiles)
        {
            ProcessFile(file);
        }
    }

I have been reading about Task Parallel library but not that confident. 我一直在阅读有关任务并行库但没有那么自信。 Not that very glued up on threading. 不是那么强调线程。 It seems that TPL wraps lots for me. 似乎TPL为我包装很多。

To put it simply is it just a case of using parallel.Foreach? 简单来说就是使用parallel.Foreach的情况呢?

any sample or suggestions 任何样品或建议

Yes, it might be as simple as replacing foreach with Parallel.ForEach . 是的,它可能就像用Parallel.ForEach替换foreach一样简单。

You have to remember that multiple threads would now be executing ProcessFile concurrently. 您必须记住,多个线程现在将同时执行ProcessFile

So, if you are writing to any shared state in that method, you will have to use synchronization constructs to protect it. 因此,如果您要写入该方法中的任何共享状态,则必须使用同步构造来保护它。

If you're new to multi-threading, there's a great introductory ebook you should read here: Albahari 如果您不Albahari多线程,那么您应该阅读一本很棒的入门电子书: Albahari

Hope it is helpful to you. 希望它对你有所帮助。 Simple snippet to demo how to move the file in parallel. 简单的代码片段,演示如何并行移动文件。

        List<FileInfo> files = new List<FileInfo>();
        files.Add(new FileInfo("F:\\1.xml"));
        files.Add(new FileInfo("F:\\2.xml"));
        files.Add(new FileInfo("F:\\3.xml"));



        Parallel.ForEach(files, f =>
        {
            f.MoveTo("d:\\test\\" + f.Name); 
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM