If your VSTO solution crashes after running for a while…

…and the problem isn’t reproducible.

I was confronted with a request to trouble-shoot such a situation, not long ago. A large organization contacted me and this was the problem description. More than 10,000 lines of code performing a number very complex tasks in Word, called by the user from a multi-paged Taskpane. Truly impressive! If it weren’t for the fact that Word was crashing unpredictably, but usually only after the VSTO tool had been running for some length of time.

Uncertain whether I would be able to help, I made the 4-hour trip to the offices and sat down with the developer. He took the tool through its paces… and Word crashed when he wanted to close it. And again, and again. We took a closer look at the code executing on Word’s Quit event and discovered that COM objects were being forcibly released, including the Application object:


There are two points to this. One is that VSTO cleans up after itself and takes care of releasing COM objects related to the project for the developer. So such code generally isn’t needed. Setting objects to Nothing / null and using standard garbage collection is enough. The other is that forcibly releasing the Word.Application object while a VSTO solution is still running will “orphan” these objects so that VSTO can no longer work with them as it is designed to do when the application quits.

The search for further possible causes continued, until we broke for lunch. The topic of why I was there came up and discussion veered to the project – everyone at the table being aware of the problems with the tool. The developer was describing something, I was thinking about the morning’s work and caught the phrase “New Document”. That got my complete attention and set alarm bells ringing!

Back in front of the 3 monitors, we searched and indeed found a line wdDoc = New Document().

In Office object model development the only time the keyword New is used/allowed is with the Application object, in order to start a new instance of the Office application. The correct way to create things inside the application is the Add method, so for a new document: Application.Documents.Add().

But for some reason unknown outside Microsoft, Word accepts New Document and creates a Document object in memory. The problem is, once the Document object has been created, it’s never visible in Word and it can’t be removed from memory – except by quitting the Word instance. Accumulate enough of these in memory and Word will crash.

After replacing New Document with Documents.Add Word never crashed again that day. I haven’t heard anything since, so I’m optimistic that the tool is now running smoothly.

So if you’re having problems with Word crashing unpredictably, check your solution for

  • code forcibly releasing COM objects that VSTO is still working with
  • New Document()

Leave a Reply