Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure the correct state of local variables when using BeginInvoke method

Tags:

c#

winforms

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.

like image 381
FrozenHeart Avatar asked Aug 18 '15 10:08

FrozenHeart


1 Answers

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.

like image 130
nvoigt Avatar answered Sep 21 '22 12:09

nvoigt