Calling Synchronous Methods Asynchronously

Using the BeginInvoke function is way to much fun and something that entry level C# programmers get their hands on fairly quickly. That doesn’t mean it doesn’t have its pitfalls as most don’t bother to read the documentation.

The Microsoft article clearly states:

  • No matter which technique you use, always call EndInvoke to complete your asynchronous call
  • EndInvoke blocks the calling thread until it completes

In situations where a blocking call is not a problem it is a quick and easy fix, but in most situations it just becomes tedious to clean up after yourself.

        public static void AutoEndInvoke(this IAsyncResult result, ISynchronizeInvoke control)
            Task task = Task.Factory.StartNew(() => { AutoEndInvokeTask(result, control); }, TaskCreationOptions.PreferFairness);
            task.ContinueWith(t => HandleException(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
        private static void AutoEndInvokeTask(IAsyncResult result, ISynchronizeInvoke control)

Using the code is easy to:

            _window.BeginInvoke(new Action(OpenFileWindow)).AutoEndInvoke(_window);

It isn’t the cleanest of solutions, it spoils a whole thread so it might not be the best solution for very heavy situations (bulk loading invokes works way better in those cases). But it does alleviate most of the occasional BeginInvoke calls.