3.19. Adding a Notification Callback Using an Interface
Problem
You need a flexible, well-performing callback mechanism that does not make use of a delegate because you need more than one callback method. So the relationship between the caller and the callee is more complex than can easily be represented through the one method signature that you get with a delegate.
Solution
Use an interface to provide callback methods. The
INotificationCallbacks
interface contains two methods that will be used by a client as
callback methods. The first method,
FinishedProcessingSubGroup, is called when an
amount specified in the amount parameter is
reached. The second method,
FinishedProcessingGroup, is called when all
processing is complete:
public interface INotificationCallbacks
{
void FinishedProcessingSubGroup(int amount);
void FinishedProcessingGroup( );
}The NotifyClient class implements the
INotificationCallbacks interface. This class
contains the implementation details of each of the callback
methods:
public class NotifyClient : INotificationCallbacks
{
public void FinishedProcessingSubGroup(int amount)
{
Console.WriteLine("Finished processing " + amount + " items");
}
public void FinishedProcessingGroup( )
{
Console.WriteLine("Processing complete");
}
}The Task class is the main class that implements
its callbacks through the NotifyClient object. The
Task class contains a field called
notificationObj, which stores a reference to the
NotifyClient object that is passed to it either through ...