Search code examples
c#asynchronoustask-parallel-libraryasyncsocket

Can I convert the following to TPL code?


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:

  1. How can I do this:

  2. Do I actually want to do this? Would it be beneficial to performance?


Solution

  • Your foreach loop written as Parallel.ForEach. Approximately.

    Parallel.ForEach(registeredObservers, (obs, item) =>
            {
                if (obs != null) 
                   obs.OnMessageReceivedEvent(new ObserverEvent(item));
            });