It does sound like you want an event. In .NET, an event is just a delegate which by convention has a special signature. Here is a C# example of declaring an event in a class:
public class MyObject
{
// ...
public event EventHandler ProcessingComplete;
// ...
}
EventHandler is a delegate with two parameters:
public delegate EventHandler(object sender, EventArgs e);
The sender is the object which raised the event and the EventArgs encode any information you want to pass to an event subscriber.
Every event is expected to follow this convention. If you wish to communicate specialized information for your event, you can create your own class derived from EventArgs. .NET defines a generically typed EventHandler delegate for this purpose, EventHandler<TEventArgs>
. C# example:
class ProcessingCompleteEventArgs : EventArgs
{
public ProcessingCompleteEventArgs(int itemsProcessed)
{
this.ItemsProcessed = itemsProcessed;
}
public int ItemsProcessed
{
get;
private set;
}
}
// ...
// event declaration would look like this:
public event EventHandler<ProcessingCompleteEventArgs> ProcessingComplete;
To subscribe to an event, use the +=
operator. To unsubscribe, use the -=
operator.
void Start()
{
this.o = new MyObject();
this.o.ProcessingComplete += new EventHandler(this.OnProcessingComplete);
// ...
}
void Stop()
{
this.o.ProcessingComplete -= new EventHandler(this.OnProcessingComplete);
}
void OnProcessingComplete(object sender, EventArgs e)
{
// ...
}
Inside your class, to fire the event, you can use the normal syntax to invoke a delegate:
void Process()
{
// ...
// processing is done, get ready to fire the event
EventHandler processingComplete = this.ProcessingComplete;
// an event with no subscribers is null, so always check!
if (processingComplete != null)
{
processingComplete(this, EventArgs.Empty);
}
}