0

I have some application that passes a string parameter to a method that is invoked using a thread inside a loop like this, this thread is create 50 times

Thread t = new Thread(new ThreadStart(() =>
{
    StartExtraction( savedFileName);
}));
t.Name = "do";
t.Start();

in the StartExtraction method I noticed that the parameters are overwritten , I mean if the first invocation was with savedFileName="abc" and the second was with savedFilename="xyz" ,the method always processes "xyz", I mean StartExtraction when debugged, the parameter is overwritten, , why?

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321

2 Answers2

2

why?

Because that is how closure works. It closes over the variable, not the value. If you change the value of savedFileName, that is what you'll see inside the captured delegate.

In order for this to set the expected value, you'll need to store it inside a local variable inside your captured lambda:

Thread t = new Thread(new ThreadStart(() =>
{
    var temp = savedFileName;
    StartExtraction(temp);
}));
t.Name = "do";
t.Start();
Community
  • 1
  • 1
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
1

Adding to what has already been answered, you would need to store the value of savedFileName into a temporary variable within your loop and use that instead of savedFileName in order to avoid the closure.

As an example see the answer already provided here:

Captured variable in a loop in C#

Community
  • 1
  • 1
Ric
  • 12,855
  • 3
  • 30
  • 36