1
\$\begingroup\$

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 */
                    }
                });
            });
        }
    }
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

I think that unless benchmarking proves otherwise, you should simply OnData?.BeginInvoke() and just let the thread pool handle it for you.

\$\endgroup\$
2
  • \$\begingroup\$ The answer was to benchmark it. I guess laziness came over me after a long day and thought it would be easier to ask the question than benchmark it. The code snippet in question came out quickest. I made a slight adjustment by moving the json parsing logic to inside the task as if there are no subscribers it's wasting computational time. I'll mark this as answer on the basis of the benchmarking comment and a kick up the ass to write some code! Thanks \$\endgroup\$
    – Adam H
    Commented May 4, 2020 at 11:53
  • \$\begingroup\$ Didn't mean to kick no one's ass :) I'm a bit surprised because I expected that BeginInvoke() would perform better. Was the difference significant? \$\endgroup\$
    – asaf92
    Commented May 4, 2020 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.