Access to modified closure

Thursday, October 1, 2009

Resharper is a fantastic tool and gives plenty of warnings that shouldn’t be neglected. One warning I want to describe here is “Access to modified closure”:
private void WriteString(string str)
{
 var newMsg=string.Format("New message: {0}", str);
 _syncContext.Post((param) => listBox1.Items.Add(newMsg), null);
 newMsg=String.Empty;
}
WriteString is called by a non UI Thread, hence the SynchronizationContext. The question I’ve been asking myself is: “Why can’t I access the variable newMsg from within my lambda?” The answer to that question is that if the lambda refers to a variable defined outside of its scope, the variable may be changed while the lambda is running. If you execute the example above, you’ll see that an empty text is added to the listbox, which means that the variable newMsg is changed before the lambda runs (because the post method is asynchronous). I need to pass newMsg as a parameter to solve the problem (actually, I should pass a copy of the object, but since a String is immutable it doesn’t matter for this example)
private void WriteString(string str)
{
 var newMsg=string.Format("New message: {0}",str); 
 _syncContext.Post((param) => listBox1.Items.Add(newMsg),newMsg); 
 newMsg = String.Empty; 
} 
No more warning!

0 Comments so far - Add one:

Post a Comment