Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have location of various csv files in "strFilePath" array(almost 1000 files which have 1 million records in each file). It takes a lot of time to read from files and merge all the data to single datatable. So I decided to go forward with Parallel processing. The question is, how can I merge all the data from datatable "dt" to a global datatable "dtMerge"?

C#
DataTable dtMerge=new DataTable();
for(int i=0;i<strFilePath.Count;i++)
{
     Parallel.For(0, 3,m =>
          clsNewClass objCls=new clsNewClass();
          DataTable dt=objCls.ReadCSV(strFilePath[m+i]);
      });
      m+=3;
}
Posted

1 solution

You can try this code snippet.
C#
object padlock = new object();
DataTable dtMerge = new DataTable();
ParallelLoopResult result = Parallel.For(0, strFilePath.Count, index =>
{
    Debug.WriteLine("Iteration {0} : {1}", index, strFilePath[index]);
    clsNewClass objCls = new clsNewClass();
    DataTable dt = objCls.ReadCSV(strFilePath[index]);
    lock (padlock) // Makes sure only one merge operation is done at a time
    {
        dtMerge.Merge(dt);
    }
});
Debug.WriteLine("Result: {0}", result.IsCompleted ? "Completed Normally" : String.Format("Completed to {0}", result.LowestBreakIteration));


You should probably also look into the way you read data from the CSV file.
When you have so many files with that many lines, small inefficiencies here and there in the code will add up to a lot of time losses.
Even a millisecond per file will add up to 1 second slower time.
 
Share this answer
 
Comments
thesarath 14-Sep-14 9:42am    
Will this "lock" actually works in sequential way? Actually this "lock" ensures that only 1 process run at a time. So will this Parallel.For with "lock" work like Parallel processing or Sequential processing?
George Jonsson 14-Sep-14 11:51am    
It will lock other threads in the same process.
If in doubt, just try the code and do more debug printouts.
Debugging parallel code is always tricky.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900