2

I recently had some problems with the performance of the Word object model. In an add-in that I wrote for Word I need to parse through all the words of a document and replace some of them or ask the user for the ones that have multiple replacements. I know that it is faster to ask Word for all of the document text content at once and then process it and put it back all at once again, but this is not suitable for my add-in because I need to have access to the range objects that represent the words that have multiple replacements so that I can somehow mark them in the document and present the user with a tool tip from which he can select the replacement he wants.

So for the moment the single great speed improvement that came in my head was multithreading since most people already have dual core or better. The problem is that all the things you find on Google say that multithreading in Office is a very bad thing to do.

So is there any one who managed to do this in a manner that worked in most of its usage? By this I mean if it also worked on other PCs then the development one?

And a second Q is: Does anyone know why Microsoft restricted the Word ( Office) object model to single thread? Just out of curiosity :)

Chris Haas
  • 53,986
  • 12
  • 141
  • 274
dfasasd
  • 21
  • 1

1 Answers1

1

Multithreading in Office should work just fine. Here's an article from Microsoft on doing just that:

Walkthrough: Multithreading with the BackgroundWorker Component (C# and Visual Basic)

The Office object model isn't single threaded but rather Single Thread Apartment (STA). This is actually the default state for all VB.Net programs (C# is MTA by default). To learn more about STA vs MTA check out these links:

Community
  • 1
  • 1
Chris Haas
  • 53,986
  • 12
  • 141
  • 274
  • Actually, when you create a C# app, it adds the `[STAThread]` attribute by default... – configurator Mar 18 '11 at 13:46
  • @configurator, you're right. I could have sworn that C# used to be MTA but I just did a test in 2008 and 2010 and they both use STA. Maybe 2005 used MTA. I might have to dig up an old version and find out now. – Chris Haas Mar 18 '11 at 13:55
  • Ok, I remember now. VB through VS is by default STA behind the scenes, there's no explicit STA declaration. C# through VS needs to explicitly declare it. The CLR made a breaking change and required all `Main` methods to be run as MTA unless explicitly declared as STA. Its about a third of the way down on http://msdn.microsoft.com/en-us/netframework/aa497241.aspx – Chris Haas Mar 18 '11 at 14:03
  • It might also be the VB compiler and not just VS but I haven't had enough coffee to bother figuring that out – Chris Haas Mar 18 '11 at 14:04
  • I see the difference now. In VB, you don't need to mention STA - it adds the attribute automatically if MTA isn't provided. In C#, the attribute is shown, and if you remove it the runtime runs as MTA. – configurator Mar 18 '11 at 14:28