karim.fone
karim.fone

Reputation: 67

Pause For each until finish Thread inside C#

I'm in trouble with this code. I'm using .Net (C#) with Winform Application.

I have foreach loop for files inside directory and with each file I want to run thread with some functions.. the problem here is the loop not waiting for the thread to finish and the result is if I have 5 files, I get 5 threads run with each other making my pc freeze .. is it possible to pause the loop until the thread finish, then continue the loop for other threads ??

foreach (string f in Directory.GetFiles(txtPath.Text))
{
    Thread threadConversion = new Thread(new ParameterizedThreadStart(function name));
    threadConversion.Start(function parameter);
}

Upvotes: 1

Views: 325

Answers (3)

Lamloumi Afif
Lamloumi Afif

Reputation: 9081

You can use Parallel.ForEach method ( you must at least the version .net 4.0)

For example

 Parallel.ForEach(Directory.GetFiles(txtPath.Text), f=>
                {
                 //some code
                }
                );

Upvotes: 0

Romano Zumbé
Romano Zumbé

Reputation: 8099

You just don't need to run the method as a thread. Just run it like this:

foreach (string f in Directory.GetFiles(txtPath.Text))
{
    function(parameter);
}

Upvotes: 1

dcastro
dcastro

Reputation: 68740

If you want to read the files sequentially, why not move the whole thing inside the thread?

Thread threadConversion = new Thread(() => {
    foreach (string f in Directory.GetFiles(txtPath.Text))
    {
        //read file f
    }
});

threadConversion.Start();

Or better yet, use Tasks:

await Task.Run(() => {
    foreach (string f in Directory.GetFiles(txtPath.Text))
    {
        //read file f
    }
});

//do some other stuff

Upvotes: 3

Related Questions