Reputation: 106
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!!
Upvotes: 0
Views: 38
Reputation: 117009
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.
Upvotes: 1