0

I am saving some csv files using threads, Threads are created in a loop Here is the code

foreach (var f in Files)
{

   string tFile = f.ToString(); 
   Thread myThread = new Thread(() =>  SaveCSVFile(BulkExtractFolder, tFile));
   myThread.Start();
}

//save folder as zip file and download it

it starts saving csv files but when the zip file downloads it does not contain all files in it, because some threads are in execution when I zip this folder, How I can know that all threads started in for loop have completed their execution.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
AddyProg
  • 2,960
  • 13
  • 59
  • 110
  • 2
    By not using threads, but tasks and ContinueWith. See [C# Waiting for multiple threads to finish](http://stackoverflow.com/questions/2281926/c-sharp-waiting-for-multiple-threads-to-finish), [Running multiple async tasks and waiting for them all to complete](http://stackoverflow.com/questions/25009437/running-multiple-async-tasks-and-waiting-for-them-all-to-complete). – CodeCaster Jan 15 '16 at 13:01

3 Answers3

1

This looks like a job for Parallel.ForEach https://msdn.microsoft.com/en-us/library/dd460720(v=vs.110).aspx

Parallel.ForEach(Files, (f)=> {
   string tFile = f.ToString(); 
   SaveCSVFile(BulkExtractFolder, tFile);
});

And here is how you limit the number of threads: How can I limit Parallel.ForEach?

Edit: For older versions of .NET, this will work:

var numFiles = Files.Count; //or Files.Length, depending on what Files is
var threads = new Thread[numFiles];
for(int i = 0; i < numFiles; i++)
{
    threads[i] = new Thread(() =>  SaveCSVFile(BulkExtractFolder, Files[i]));
    threads[i].Start();
}
for(int i = 0; i < numFiles; i++)
{
    threads[i].Join();
}    
Community
  • 1
  • 1
Alex
  • 14,338
  • 5
  • 41
  • 59
0

If you are using .Net 4 or higher, you may use Task instead of Thread and WaitAll method.

List<Task> tasks = new List<Task>();
foreach (var f in Files)
{
   string tFile = f.ToString(); 
   tasks.add(Task.Factory.StartNew(() =>
        {               
             SaveCSVFile(BulkExtractFolder, tFile)
        });
   );
}

Task.WaitAll(tasks.toArray());
daryal
  • 14,643
  • 4
  • 38
  • 54
0

If you are zipping/downloading the files in main thread then you can join all your child threads using Thread.Join() method. In which case, main thread will wait until all other threads have completed.

foreach (var f in Files)
{
   string tFile = f.ToString(); 
   Thread myThread = new Thread(() =>  SaveCSVFile(BulkExtractFolder, tFile));
   myThread.Start();
   myThread.Join();
}
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • If you're going to wait immediately after starting the thread you might as well just do all of the work in the current thread. – Servy Jan 15 '16 at 13:57