When you call MethodInvoke
it will not occurs at that moment, but some time later.
In your scenario you have a chance of following to occurs:
- invoked code is finally executed;
- the loop is already finished (and
i
become 101) - you are accessing
i
directly and you read 101.
And to fix it you can make a copy of i
(by passing it as a parameter to invoked method):
pbLoad.BeginInvoke(new Action<int>(a =>
{
if (!stopExecution)
{
pbLoad.Value = a;
Debug.WriteLine(a); //a to output window
}
}), new object[] { i });
P.S: you don't need to check for InvokeRequired
, unless you plan to call DoDomethingThatTakesAWhile
method directly, which I assume is not the case.