Race conditions with captured variables

Chapter 15: Asynchrony with async/await: 15.4

Created: 3/9/2014
Last updated: 3/9/2014

This isn't really specific to asynchronous functions, but it's worth knowing that any time you capture variables and use them in multiple concurrent tasks, you have a race condition waiting to happen. That can occur if you capture the same local variable in multiple anonymous functions, or if you create a single delegate which captures a local variable, and then execute that delegate in multiple threads.

This isn't new, but if you're used to local variables being inherently thread-safe (due to being "owned" by a single thread) then it's something to watch out for.

Basically, the same golden rule applies as normal: using mutable state within multiple threads is very error-prone, and should be avoided where possible.