I'm trying to create COM component, where it will be frequently call by a excel application (excel will load the COM at its initialization) and another process (let say procA) also sends (with high frequency) windows messages to this component. Currently I implemented COM as a STA, however, I experienced that while COM is busy with processing messages from procA,开发者_如何学JAVA the excel UI get stuck.
Please help me to get around this problem. Can I just create a simple window thread to process messages from procA while keeping COM as STA model ? Or do I need to make COM as MTA model, if so please explain how to handle it .
Thank You
Moving to an MTA requires you to perform all necessary locking to protect the state of your component. And it will add thread switch overhead because Excel's UI runs on a specific thread, which will block1 while calling cross thread into your component. The other process is already incurring the cross process overhead so no real change there.
You could avoid the Excel cross-thread overhead by marking your component model as threading model 'Neutral'—it can still be used from any thread while not being tied to exist in the MTA (i.e. all in process calls will be direct, no thread swicthes). Write it as free threaded (all the locking is still needed) but just change the registration.
Given all the effort to ensure your component is thread safe you may find there is no advantage unless multiple calls into your component can really run concurrently. If you just take a lock for the duration of each method you are not saving anything over being in an STA. Finer grained locking might give an advantage, but you need more detailed analysis of what concurrency is possible, and then profiling to prove you have been able to achieve it. A look at Amdahl's Law will cover these issues.
1 This is very simplistically put... the real situation is rather more complex.
精彩评论