0% found this document useful (0 votes)
36 views2 pages

Page 059

The document outlines a C# implementation for managing message observers, including methods to unregister observers and dispatch messages to registered listeners. It provides a mechanism to ensure that only valid observers receive messages, while also handling potential null references. The code includes safety checks and logging for debugging purposes.

Uploaded by

Imogen Claydon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views2 pages

Page 059

The document outlines a C# implementation for managing message observers, including methods to unregister observers and dispatch messages to registered listeners. It provides a mechanism to ensure that only valid observers receive messages, while also handling potential null references. The code includes safety checks and logging for debugging purposes.

Uploaded by

Imogen Claydon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

Folder Structure and C# File Contents

if ([Link])
[Link](type);
}
/// <summary>
/// Unregisters the interface as a receiver for the type of Message T.
/// </summary>
/// <typeparam name="T">Must inherit from Message.</typeparam>
/// <param name="receiver">The receiver that must be unregistered.</param>
public void UnregisterObserver<T>(IMessageReceiver receiver) where T : Message
{
Type type = typeof(T);
Observers observers = null;
if( ![Link](type, out observers) )
{
[Link]("Unable to unregister receiver. <"+[Link]+"> the type isn't
registered.");
return;
}
//Remove receiver
[Link](receiver);
if ([Link])
[Link](type);
}
/// <summary>
/// Dispatch the message to every object registered as listener of the type of
message.
/// </summary>
/// <param name="msg">Message to be dispatched.</param>
public void Dispatch(Message msg)
{
//Find the registered message with type T
foreach (Observers observers in CollectValidObservers(msg))
{
DispatchSafe(msg, [Link]);
DispatchSafe(msg, [Link]);
}
}
/// <summary>
/// Static method that will dispatch the given Message msg to every object in the
list of receivers.
/// </summary>
/// <param name="msg">Message to be dispatched.</param>
/// <param name="list">The list of receivers to dispatch the message.</param>
static public void DispatchSafe(Message msg, List<IMessageReceiver> list )
{
int count = [Link];
for (int i = 0; i < count; i++)
{
IMessageReceiver listener = list[i];
if (listener == null)
{
[Link]("listener is null. Leaked an unregister?");
[Link](i);
i--;
}
else
[Link](msg);
}
}

You might also like