c# - Foreach Variable in Closure. Why Results Differ for These Snippets? -
this question has answer here:
can explain why snippet:
// create required tasks foreach (var messagetosend in messagestosend) { emailmessage messagetobesent = messagetosend; task<bool> processingtask = new task<bool>(() => sendmessage(messagetobesent)); processingtask.start(); }
works differently one:
// create required tasks foreach (var messagetosend in messagestosend) { task<bool> processingtask = new task<bool>(() => sendmessage(messagetosend)); processingtask.start(); }
in first snippet tasks start own message, while in second 1 tasks start same message?
resharper gives description: "access foreach variable in closure. may have different behaviour when compiled different versions of compiler." why may have different behaviour?
resharper gives description: "access foreach variable in closure. may have different behaviour when compiled different versions of compiler." why may have different behaviour?
there breaking change between c# 4 , c# 5 due way loop variable in foreach impacted closures, notably since introduction of lambda expressions in c# 3. resharper warning of this, in case might depend or otherwise have come expect former semantics.
the quick upshot in c# 4, loop variable shared between each iteration of loop, , closures capture variable, led unexpected results people when closed on loop variable.
in c# 5, each iteration of loop gets own variable, closures in 1 iteration not close on same variable other iterations, leading more expected outcomes (for people).
that gets heart of problem:
in first snippet tasks start own message, while in second 1 tasks start same message?
in first snippet, creating copy of loop variable inside loop , closure occuring on inner variable. in second, close on loop variable directly. presumably, running under c# 4, former semantics apply. if running in c# 5, loop outputs both versions should consistent. change resharper refers to, , should let understand how structure code in c# 4 (namely, use first version have written).
as justin pihony points out in comments, eric lippert has written very useful blog article on former semantics alludes change c# 5.
Comments
Post a Comment