KeyLimeTie Blog

Item 21: Express Callbacks with Delegates

By Brian Pautsch – 8/1/2005 6:26:20 PM. Posted to Thoughts.

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 common use of delegates is events, that should not be the only time you use this language feature. Delegates let you configure the target at runtime and notify multiple clients. A delegate is an object that contains a reference to a method. When performing multicast delegation, be sure to invoke each delegate target yourself. Each delegate you create should contain a list of delegates. To examine the chain yourself and call each one, iterate the invocation list yourself like s
1public delegate bool ContinueProcessing();
2
3public void LengthyOperation(ContinueProcessing pred)
4{
5 bool bContinue = true;
6
7 foreach (ComplicatedClass cl in mobjContainer)
8 {
9  cl.DoLenghtyOperation();
10  foreach (ContinueProcessing pr in pred.GetInvocationList())
11  {
12   bContinue &= pr();
13   if (!bContinue)
14    return;
15  }
16 }
17}
In the above example, I've defined the semantics so that each delegate must be true for the iteration to continue.

These are just a few reasons why...to read more, pick up "Effective C#: 50 Specific Ways to Improve Your C#" by Bill Wagner

You can buy it at the Addison-Wesley website: http://www.aw-bc.com/

Comments

Leave a Comment

Name:
Email:
URL:
Comment:
Security Code:
Type Security Code:

Photos on Flickr

More Photos »

Search Blog


Get Email Updates

Like what you read here at KeyLimeTie? Sign up for our email list!

Subscribe