Should I be concerned about "access to modified closure" in a linq queries?
I have a linq query that is showing an error:
I see this error any time I try to access the variable I'm iterating over, if开发者_如何学JAVA the source of the collection is a linq query. I guess this error is just telling me the variable could change, or something like that?
This error is telling you that the reference to pubConfig
inside your query will be using the value of pubConfig
at the time the query is evaluated, and not at the time where you define it and store it in pubConfigSettings
.
In practical terms, you will be OK if the query is evaluated "on the spot". If you keep it around for later evaluation, and the value of pubConfig
changes in the meantime, you will encounter unexpected results.
You are closing over the loop variable which is considered harmful. The query references the variable, not the value the variable had had when the query was created. It's not clear whether or not it will cause you a problem in your specific code example (it depends on what you do with the query you have created), but in general you should avoid this because it can cause difficult to debug problems.
A simple solution is to take a copy of the loop variable before referencing it in your query.
foreach (var pubConfig in ...)
{
var pubConfig2 = pubConfig;
// Use pubConfig2 instead of pubConfig in the query.
}
It's no problem as long as the variable doesn't get modified during the lifetime of the lambda.
If you modify the variable and use the lambda again then the lambda will get the new value of the variable which can be confusion or even not threadsafe.
To get rid of the warning you can create a variable in the inner scope copying the variable from the outer scope and use it in the lambda.
精彩评论