Before ParameterizedThreadStart existed, if you wanted to start a new
(non-threadpool) thread and give it some information??”the URL of a page to fetch,
for instance??”you had to create an extra type to hold the URL and put the action of
the ThreadStart delegate instance in that type. It was all a very ugly way of achieving
something that should have been simple.
As another example, suppose you had a list of people and wanted to write a
method that would return a second list containing all the people who were under a
given age. We know about a method on List
that returns another list of everything
matching a predicate: the FindAll method. Before anonymous methods and captured
154 CHAPTER 5 Fast-tracked delegates
variables were around, it wouldn??™t have made much sense for List.FindAll to
exist, because of all the hoops you??™d have to go through in order to create the right
delegate to start with. It would have been simpler to do all the iteration and copying
manually. With C# 2, however, we can do it all very, very easily:
List FindAllYoungerThan(List people, int limit)
{
return people.FindAll (delegate (Person person)
{ return person.Age < limit; }
);
}
Here we??™re capturing the limit parameter within the delegate instance??”if we??™d had
anonymous methods but not captured variables, we could have performed a test against
a hard-coded limit, but not one that was passed into the method as a parameter.
Pages:
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315