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.

1

3 Answers 3

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();
}    
Sign up to request clarification or add additional context in comments.

1 Comment

The application I am working on is in MVC2 with Dot Net 3.5
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();
}

1 Comment

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

1 Comment

The application I am working on is in MVC2 with Dot Net 3.5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.