0

I am calling a function using parameterised thread

ParameterizedThreadStart ts = delegate(object o) { ProcessDBThread(strDBName, dicMsg, objQueueItem.RunID); };

Hence the ts variable should logically contain all 3 parameters that I am passing, but it is only holding one parameter.

The above code is inside a loop hence the rest two parameter gets overridden by the latest value. As a result all the Parameterized Thread contains different dicMsg but same strDBName. In reality strDBName is different for every case.

I have checked the ts value in quick watch; ((System.Delegate)(ts)).Target Here the Target contains only one parameter, where it should have been three.

Just point me out where I might have been gone wrong!!

AlG
  • 14,697
  • 4
  • 41
  • 54
Abhijit_Srikumar
  • 106
  • 1
  • 13
  • It would be awesome if you showed us all of the code. A [mcve] is worth a million bucks to us. – Enigmativity Feb 23 '16 at 13:39
  • I understand your point of view but i am not able to post the whole code because its quite lengthy and not readable. Anyways your answer is working fine. – Abhijit_Srikumar Feb 23 '16 at 14:37
  • It's not a point of view, it's what is expected for a good question here on Stack Overflow. You should read [ask] and [mcve]. – Enigmativity Feb 23 '16 at 23:24

1 Answers1

1

Try this inside your loop:

var dbn = strDBName;
var msg = dicMsg;
var rid = objQueueItem.RunID;
ParameterizedThreadStart ts = delegate (object o)
{
    ProcessDBThread(dbn, msg, rid);
};

When you have code like this:

for (var i = 0; i < 10; i++)
{
    ParameterizedThreadStart ts = delegate (object o) { Console.WriteLine(i); };
    ts.Invoke(null);
}

...the time it takes to start the threads is far longer than the time to take the for loop to finish so the value of i in the thread delegate becomes 10 before any of the threads start.

So by doing this:

for (var i = 0; i < 10; i++)
{
    var j = i;
    ParameterizedThreadStart ts = delegate (object o) { Console.WriteLine(j); };
    ts.Invoke(null);
}

...you capture a copy of i in j and that doesn't change (because it is inside the loop's scope) so the parameters work correctly.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172