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

Recommended Answers

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.[code]foreach (string s in fileEntries) {
string temp = s;
t = new Thread(() => Shrink(temp));
t.Start();
}[/code]

Jump to Post

All 2 Replies

Re: Looping for crearing new thread everytime doesn't work 80 80

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();
}
Re: Looping for crearing new thread everytime doesn't work 80 80

Yup .. that worked.
Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.