Variable capturing
Before I start writing parallel code, I have to cover something completely different. As you’ll see in this chapter, a big part of the incredible usefulness of tasks and patterns is the ability to use them in combination with anonymous methods and variable capturing. As powerful as that combination is, however, it also brings in some problems.
The code in this chapter will frequently run into the problem of capturing a loop variable. Instead of trying to explain this problem at the same time as dealing with the already hard concepts of parallel code, I decided to write a simple program that demonstrates the problem and does nothing more.
The code in the AnonMethod
project tries to write out the numbers from 1 to 20 in a convoluted way. For each value of i
, the code calls TThread.ForceQueue
, and passes in an anonymous method that calls Log(i)
to write the value into ListBox
.
The problem with the following code lies in the programmer’s assumptions...