简体   繁体   中英

Stop Execution utill all threads created in a for loop are terminated C#

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.

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();
}    

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());

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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