Information Technology Reference
In-Depth Information
to interrupt me periodically when he had an important (or even unim-
portant) status to report or needed my assistance. Callbacks are used to
provide feedback from a server to a client asynchronously. They might
involve multithreading, or they might simply provide an entry point for
synchronous updates. Callbacks are expressed using delegates in the C#
language.
Delegates provide type-safe callback definitions. Although the most com-
mon use of delegates is events, that should not be the only time you use
this language feature. Anytime you need to configure the communication
between classes and you desire less coupling than you get from interfaces,
a delegate is the right choice. Delegates let you configure the target at run-
time and notify multiple clients. A delegate is an object that contains a ref-
erence to a method. That method can be either a static method or an
instance method. Using the delegate, you can communicate with one or
many client objects, configured at runtime.
Callbacks and delegates are such a common idiom that the C# language
provides compact syntax in the form of lambda expressions to express del-
egates. In addition, the .NET Framework library defines many common
delegate forms using Predicate<T>, Action<>, and Func<>. A predicate is
a Boolean function that tests a condition. A Func<> takes a number of
parameters and produces a single result. Yes, that means a Func<T, bool> has
the same form as a Predicate<T>. The compiler will not view Predicate<T>
and Func<T, bool> as the same though. Finally, Action<> takes any num-
ber of parameters and has the void return type.
LINQ was built using these concepts. The List<T> class also contains
many methods that make use of callbacks. Examine this code snippet:
List < int > numbers = Enumerable .Range( 1 , 200 ).ToList();
var oddNumbers = numbers.Find(n => n % 2 == 1 );
var test = numbers.TrueForAll(n => n < 50 );
numbers.RemoveAll(n => n % 2 == 0 );
numbers.ForEach(item => Console .WriteLine(item));
The Find() method takes a delegate, in the form of a Predicate<int> to
perform a test on each element in the list. It's a simple callback. The Find()
method tests each item, using the callback, and returns the elements that
 
Search WWH ::




Custom Search