简体   繁体   English

停止执行直到在for循环中创建的所有线程都终止C#

[英]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 我正在使用线程保存一些csv文件,线程是在循环中创建的这是代码

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. 它开始保存csv文件,但是在下载zip文件时,它并不包含其中的所有文件,因为当我压缩此文件夹时,某些线程正在执行中,我如何知道for循环中启动的所有线程都已完成执行。

This looks like a job for Parallel.ForEach https://msdn.microsoft.com/en-us/library/dd460720(v=vs.110).aspx 这看起来像是Parallel.ForEach的工作https://msdn.microsoft.com/zh-cn/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? 这是您如何限制线程数: 如何限制Parallel.ForEach?

Edit : For older versions of .NET, this will work: 编辑 :对于.NET的旧版本,这将起作用:

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. 如果使用的是.Net 4或更高版本,则可以使用Task而不是ThreadWaitAll方法。

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. 如果要压缩/下载主线程中的文件,则可以使用Thread.Join()方法加入所有子线程。 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();
}

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

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