I have a questions as to the proper way to structure the code below.
This snippet of code is used within a socket class which is intended to be a high performance socket. Many data handlers subscribe to this sockets OnData
event to handle different types of data. Ideally, I'm trying to kick the data handlers off in a task and in parallel where the HandleData
method is invoked once the socket has received data.
1) Should I make this method async and await the task?
2) Should I capture a copy of the delegates inside the task?
3) Is there a better way to accomplish this?
private void HandleData(string message)
{
var data = JObject.Parse(message);
var delegates = OnData?.GetInvocationList();
if (delegates != null)
{
Task.Run(() =>
{
Parallel.ForEach(delegates, d =>
{
try
{
d.DynamicInvoke(data);
}
catch (Exception)
{
/* Ignore */
}
});
});
}
}