Something happens in my system on a worker thread. Let’s say that the state changes. I want to handle the new state in the UI thread, so I dispatch a delegate to be invoked there:
var state = GetState();
Dispatcher.BeginInvoke(() => StateChanged(state));
When StateChanged executes on the UI thread, can I then be sure that the value of the parameter state is the value returned by GetState() before the dispatch, or will the temporary state variable be optimized away so that GetState() is called on the UI thread to populate the StateChanged parameter?
No
statewon’t be optimized away.However, Before is actually the tricky part about this question. As long as you are not changing the state variable after (in the same scope) you have nothing to worry about.
In the code above
statewon’t be optimized away. It does not mean, however, thatStateChangedwill be invoked with value 2. It could be 3, if the worker thread completes execution before starting the dispatcher thread.The main point here is that variable capturing insures that the value is preserved for the use of the closure, but that does not mean that the value is immutable.