You don't have to worry about this. The compiler generates a class
which is used to make the call to the anonymous delegate (which has the
method that is called). This class also will have members for the class
that contains this method (a field that ends in "this") as well as a member
for the iCopy variable.
In each iteration of the loop, a new instance of this class is created,
with the iCopy member field set, before the method to call is passed to
BeginInvoke.
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
-
(E-Mail Removed)
"Dean Shimic" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
> void DisplayLines(object state)
> {
> for (int i = 0; i < 500; ++i)
> {
> int iCopy = i;
> rtb.BeginInvoke((MethodInvoker)delegate
> {
> rtb.AppendText(iCopy + "\n");
> });
> }
> MessageBox.Show("Done");
> }
>
> I call this function from the main thread with ThreadPool's
> QueueUserWorkItem method. Since I'm accessing RichTextBox variable rtb
> from
> the different thread than the one it was created on I have to call
> BeginInvoke method.
>
> Above code seems to work fine but I'm not sure if it's guaranteed to since
> iCopy, the variable that is accessed from within the delegate, potentially
> goes out of scope before delegate is invoked. Does this mean that iCopy
> can
> be destroyed prior to delegate accessing it?