Using Dispatcher.BeginInvoke with current foreach member

  • Thread starter Thread starter Andrus
  • Start date Start date
A

Andrus

I tried code below but assertion fails since col value has changed .

How to fix this code so that BeginInvoke is called with definition time col
value in for loop ?

Andrus.

partial class MyUserControl : UserControl

public CreateFields() {

foreach (FormField col in MyFields ) {
if (col.Andmeklass == "Kiirvalik")
{
Dispatcher.BeginInvoke(() =>
{
Debug.Assert(col.Andmeklass == "Kiirvalik");
col.LoadPickListToCacheAsync();
});
}
}

}

}
 
Andrus said:
I tried code below but assertion fails since col value has changed .

How to fix this code so that BeginInvoke is called with definition time
col value in for loop ? [...]

The "col" variable in your loop exists outside the scope of the loop
block, and thus for the purposes of capturing in your anonymous method
is instantiated only once. Each anonymous method delegate dispatched by
BeginInvoke() is using the same variable. Thus, its value may change
before the delegate can be invoked.

You've got two options:

-- Use Dispatcher.Invoke() instead, so that the anonymous method's
execution is guaranteed to complete before the loop variable changes

-- Declare a new variable inside the loop, assigned to the value of
the loop variable, and then use that new variable in your anonymous
method instead of the loop variable

Personally, I would prefer the former approach. Only if there's some
absolute necessity in allowing the anonymous method to be dispatched
asynchronously would I introduce a new variable to the loop.

Pete
 
Back
Top