how to seprate an array to 4 segment and print it by 4 thread

48 views Asked by At

I have an array that is some text files path. I want to copy those paths to another folder. by one thread for example execute in 6 seconds. Do you think that if I use for example 4 threads it can be optimized or not ? and also how I can do that ?
I want to seperate that array to 4 segments and every thread copy its segment path. It's my code that first search *.txt files in special directory and then copy all of them to another folder.

string format = "*.txt";
string directory = lblDirectory.Text;
// it's path of first folder that i search text file in it
DirectoryInfo info = new DirectoryInfo(directory);
if ((info.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
{
    Thread t;
    string[] files = Directory.GetFiles(directory, format, 
                SearchOption.AllDirectories);
    foreach (var item in files)
    {
        streamWriter.Write(Path.GetFullPath(item) + "\r\n");
        File.Copy(Path.GetFullPath(item), Path.Combine(index, 
        Path.GetFileName(item)), true);
    }
}
1

There are 1 answers

0
Dmitry Bychenko On

I suggest using Parallel Linq (PLinq) and let .Net split the work for you, something like this:

  Directory
   .EnumerateFiles(directory, format, SearchOption.AllDirectories)
   .AsParallel()
   .WithDegreeOfParallelism(4)
   .ForAll(item => {
      //TODO: be sure that streamWriter.Write is thread safe!
      streamWriter.Write(Path.GetFullPath(item) + "\r\n");

      File.Copy(Path.GetFullPath(item), 
                Path.Combine(index, Path.GetFileName(item)), 
                true);
   });