Home > database >  Asynchronous delegates: performance in modern .NET world
Asynchronous delegates: performance in modern .NET world

Time:12-23

There is a legacy project. There are a lof of Asynchronous delegates and code like this:

IAsyncResult result = startDelegate.BeginInvoke(param1,
                param2,
                new AsyncCallback(CallbackMethod),
                null);

or just completely parameterless calls like

IAsyncResult result = startDelegate.BeginInvoke(CallbackMethod,null);

The main purpose of desired refactoring is: performance. Many places in the project has been optimized a lot and now it's time for async stuff. From performance point of view: is there any sense to migrate from Async delegates calls to:

  1. ThreadPool.QueueUserWorkItem for parametless calls
  2.  BackgroundWorker to report progres to GUI (now GUI subcribes to events in async code)
  3. Rewrite some parts to async await?

so, general question: how bad (or not bad) from performance point of view Async delegates in compare with 1)-3) above?

CodePudding user response:

The main purpose of desired refactoring is: performance.

You almost certainly won't see noticeable performance gains from changing this. However, there are two major benefits for replacing Delegate.BeginInvoke calls:

  1. Maintainability. async/await is the style of asynchronous programming that is most maintainable.
  2. Portability. Last I checked, .NET Core doesn't support Delegate.BeginInvoke, so if you ever move from .NET Desktop Framework to .NET Core, you'll need to change this code. Side note: there are some pretty good performance benefits just from migrating to .NET Core.

If you do choose to remove the calls to BeginInvoke, I recommend using Task.Run. It's a modern solution.

  • Related