Ok, after your fourth edit you provide us with an example, that exhibits a problem, sure, but not the problem you're asking for help about.
What you're saying in the question is that:
- I use BeginInvoke on a delegate variable, then change the variable, and somehow my delegates are invoked twice
What you exhibit in the posted code is that:
- I capture a loop variable in an anonymous method, and somehow I use the wrong variable value
THESE ARE NOT THE SAME PROBLEM!
The reason for your posted code misbehaving is that the code in question actually looks like this under the hood:
int i;
for (i = 0; i < 10; i++)
... create delegate, capture i, spawn thread
Here you're capturing the same variable for all the threads. If a thread doesn't start executing before the loop changes the variable, then yes, you will see the "incorrect value" for that variable.
However, if you change the code like this:
for (int i = 0; i < 10; i++)
{
int j = i;
ThreadStart threadStartObj = new ThreadStart(
delegate { PrintValueThreadFunction(j, j); });
^
|
+-- use j instead of i here
Then you will capture a "fresh" variable for each thread, which won't get changed.
So, the question remains. Is this the problem you're having? If so, then shame on you, next time, don't simplify the problem. You're wasting people's time, most of all your own. Had you posted code like the above to begin with you would've had an answer (or a duplicate question pointing to existing answers, there's plenty) within a couple of minutes.
If this is not the problem you're having, you're still having problem with an event handler like in the original code being invoked more than once, go back and produce a better example project.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…