954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Looping for crearing new thread everytime doesn't work

I am creating new thread everytime in the for loop .. but many times the loop takes the same filename and creates new thread.


Doesn't Work:

foreach (string s in fileEntries)
{
    t = new Thread(() => Shrink(s));
    t.Start();
}


I have tried individually for each file creating new thread hard coded providing the file name and it works fine.

Working / Needed:

Thread t = new Thread(() => Shrink(@"C:\abc.doc"));
t.Start();
Thread t1 = new Thread(() => Shrink(@"C:\123.doc"));
t1.Start();


But i have to take all the files in from a selected directory and create new thread for each in a loop.

Help would be appreciated.

Thanks

chintan_1671
Light Poster
39 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

Looks like you are running into the problem with capture variables. Try assigning the enumerated value to a temp variable before you use it, i.e.

foreach (string s in fileEntries) {
    string temp = s;
    t = new Thread(() => Shrink(temp));
    t.Start();
}
Momerath
Nearly a Senior Poster
3,386 posts since Aug 2010
Reputation Points: 1,232
Solved Threads: 558
 

Yup .. that worked.
Thanks

chintan_1671
Light Poster
39 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: