Make my COM assembly call asynchronous Make my COM assembly call asynchronous multithreading multithreading

Make my COM assembly call asynchronous


It is hard to tell without knowing more details, but there are few issues here.

You execute the delegate on another thread via BeginInvoke but you don't wait for it. Your try\catch block won't catch anything as it has already passed while the remote call is still being executed. Instead, you should put try\catch block inside AsyncComparedSearch.

As you don't wait for the end of the execution of remote method (EndInvoke or via callback) I am not sure how do you handle the results of the COM call. I guess then that you update the GUI from within AsyncComparedSearch. If so, it is wrong, as it is running on another thread and you should never update GUI from anywhere but the GUI thread - it will most likely result with a crash or other unexpected behavior. Therefore, you need to sync the GUI update work to GUI thread. In WinForms you need to use Control.BeginInvoke (don't confuse it with Delegate.BeginInvoke) or some other way (e.g. SynchronizationContext) to sync the code to GUI thread. I use something similar to this:

private delegate void ExecuteActionHandler(Action action);public static void ExecuteOnUiThread(this Form form, Action action){  if (form.InvokeRequired) { // we are not on UI thread    // Invoke or BeginInvoke, depending on what you need    form.Invoke(new ExecuteActionHandler(ExecuteOnUiThread), action);  }  else { // we are on UI thread so just execute the action    action();  }}

then I call it like this from any thread:

theForm.ExecuteOnUiThread( () => theForm.SomeMethodWhichUpdatesControls() );

Besides, read this answer for some caveats.