Search code examples
c#comvstooffice-interopms-project

Why is an Async Method Taking 30x Longer to Run in my VSTO Add-in


I have an MS Project VSTO add-in I'm working on. I created a WPF form and I want to click a button and show a indeterminate progress bar on the UI while a method runs. I was able to achieve this by wrapping the method in a Task.Run(), the only problem is running the method asynchronously seems to be about 30 times slower than running it normally. The method I'm calling interacts with objects from the Office.Interop.MSProject library, so I'm not sure if this is an Office or COM thing that's causing my performance woes.

private async void ButtonClickMethod()
{
    var tar = await RunTraceAnalysisAsync(); 
    // doing this takes ~30 times longer to run than just calling traceToolsController.RunTraceAnalysis() normally
}

private Task<TraceAnalysisResult> RunTraceAnalysisAsync()
{
    return Task.Run(() => { return traceToolsController.RunTraceAnalysis(); });
}

Solution

  • As a rule of thumb, most Office apps marshal calls to its object model methods back to the main thread, which is, of course, expensive. Outlook, for one, raises an exception when its detects its methods are used from a secondary thread inside the outlook.exe process.

    Try to batch all object model calls to run on the main thread (you can use Dispatcher for that).