Information Technology Reference
In-Depth Information
pass the test embodied in the predicate. The compiler takes the lambda
expression, converts that to a delegate, and uses the delegate to express the
callback.
Tr u e F o r A l l ( ) i s s i m i l a r i n t h a t i t a p p l i e s t h e t e s t t o e a c h o f t h e e l e m e n t s , a n d
determines if the predicate is true for all items. RemoveAll() modifies the
list container by removing all items for which the predicate is true.
Finally, the List.ForEach() method performs the specified action on each
of the elements in the list. As before, the compiler converts the lambda
expression into a method and creates a delegate referring to that method.
Yo u ' l l fi n d n u m e r o u s e x a m p l e s o f t h i s c o n c e p t i n t h e . N E T F r a m e w o r k . A l l
of LINQ is built on delegates. Callbacks are used to handle cross-thread
marshalling in WPF and Windows Forms. Everywhere that the .NET
Framework needs a single method, it will use a delegate that callers can
express in the form of a lambda expression. You should follow the same
example when you need a callback idiom in any of your APIs.
For historical reasons, all delegates are multicast delegates. Multicast del-
egates wrap all the target functions that have been added to the delegate in
a single call. Two caveats apply to this construct: It is not safe in the face
of exceptions, and the return value will be the return value of the last tar-
get function invoked by the multicast delegate.
Inside a multicast delegate invocation, each target is called in succession.
The delegate does not catch any exceptions. Therefore, any exception that
the target throws ends the delegate invocation chain.
A similar problem exists with return values. You can define delegates that
have return types other than void. You could write a callback to check for
user aborts:
public void LengthyOperation( Func < bool > pred)
{
foreach ( ComplicatedClass cl in container)
{
cl.DoLengthyOperation();
// Check for user abort:
if ( false == pred())
return ;
}
}
 
Search WWH ::




Custom Search