I have the following code:
string message;
while (balloonMessages.TryDequeue(out message))
{
Console.WriteLine("Outside: {0}", message);
BeginInvoke((MethodInvoker)delegate()
{
Console.WriteLine("Inside: {0}", message);
});
}
It gives me this output:
Outside: some_message
Inside:
How can I ensure that some local variables will be passed to the BeginInvoke
method as expected?
Thanks in advance.
You should make a local copy:
string message;
while (balloonMessages.TryDequeue(out message))
{
var localCopy = message;
Console.WriteLine("Outside: {0}", localCopy);
BeginInvoke((MethodInvoker)delegate()
{
Console.WriteLine("Inside: {0}", localCopy);
});
}
This way, it will always be it's own variable for each loop iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With