I have the following loop that notifies a list of observers of a certain event:
foreach (var observer in registeredObservers)
{
if (observer != null)
{
observer.OnMessageRecieveEvent(new ObserverEvent(item));
}
}
Is there A way I can use the TPL to possibly notify all the registered Observers at once?
Here is the code that is Executed in the OnMessageRecieveEvent()
public void OnMessageRecieveEvent(ObserverEvent e)
{
SendSignal(e.message.payload);
}
private void SendSignal(Byte[] signal)
{
if (state.WorkSocket.Connected)
{
try
{
// Sends async
state.WorkSocket.BeginSend(signal, 0, signal.Length, 0, new AsyncCallback(SendCallback), state.WorkSocket);
}
catch (Exception e)
{
log.Error("Transmission Failier for ip: " + state.WorkSocket.AddressFamily , e);
}
}
else
{
CloseConnection();
}
}
So my questions is:
How can I do this:
Do I actually want to do this? Would it be beneficial to performance?
Your foreach
loop written as Parallel.ForEach
. Approximately.
Parallel.ForEach(registeredObservers, (obs, item) =>
{
if (obs != null)
obs.OnMessageReceivedEvent(new ObserverEvent(item));
});