The foreach identifier and closures

前端 未结 7 1366
误落风尘
误落风尘 2020-11-22 10:51

In the two following snippets, is the first one safe or must you do the second one?

By safe I mean is each thread guaranteed to call the method on the Foo from the s

相关标签:
7条回答
  • 2020-11-22 11:22

    Your need to use option 2, creating a closure around a changing variable will use the value of the variable when the variable is used and not at closure creation time.

    The implementation of anonymous methods in C# and its consequences (part 1)

    The implementation of anonymous methods in C# and its consequences (part 2)

    The implementation of anonymous methods in C# and its consequences (part 3)

    Edit: to make it clear, in C# closures are "lexical closures" meaning they don't capture a variable's value but the variable itself. That means that when creating a closure to a changing variable the closure is actually a reference to the variable not a copy of it's value.

    Edit2: added links to all blog posts if anyone is interested in reading about compiler internals.

    0 讨论(0)
提交回复
热议问题