Asynchronous delegates optimization

Arsium ***** 331 Reputation points

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 )
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.
8,213 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 41,631 Reputation points

    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.