Asynchronous delegates optimization

Arsium ***** 331 Reputation points
2022-04-29T12:13:06.93+00:00

Is there something I should do to optimize my delegates ?

        private delegate int DoOperation();
        private readonly DoOperation doOperation;
        public bool stopOperation {get;set;}

        internal OperationConstr() : base()
        {
            doOperation= new DoOperation (Operation);
        }


        internal void OperationAsync()
        {
            doOperation.BeginInvoke(new AsyncCallback(EndOperation), null);
        }

        private int Operation()
        {
            //big work here
            return 0;
        }

        private void EndOperation(IAsyncResult ar) 
        {
            int result = doOperation.EndInvoke(ar);

            if (!stopOperation )
                OperationAsync();
            else
            {
                this.Dispose();
                return;
            }
        }
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,115 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 55,476 Reputation points
    2022-04-29T14:53:14.2+00:00

    Delegates by definition are going to be slower than regular code. If you have to use them then go ahead but accept the perf issues. You should profile the code. Most likely the delegate calls are not slow at all compared to everything else. Unless you can identify an actual bottleneck then there isn't much you can optimize.

    Personally I think you should consider an alternative design where you don't need a delegate. Delegates were useful in the past (and still can be) but honestly most code has moved on to better solutions including passing function arguments, using events or async/await. Delegates are not designed to be a catch all solution and other approaches may prove to be faster.

    Without further understanding what problem you're trying to solve using delegates it is hard to recommend better approaches.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.