Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

.net - COM multi-threading support

Working with COM for the first time I have got this COM dll, say ABCServer.dll, i created a RCW and added reference to it in my project. Now my application creates several threads and each thread creates certain classes from COM dll and works with them. But then each thread is waiting while other thread is working with certain class from COM dll.

The whole purpose of modifying my application was enabling multi-threading on it. Now when multithreading is happening at my side, the COM causing it to be sequential. Although each thread is creating new instances, why are they waiting for others to be processed?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If your COM component is marked as STA (single-threaded apartment) then there's nothing you can do to make it multi-threaded; the requirement of the component is that all calls to it are serialized onto the thread that the STA is on, and COM handles that automatically for you.

That said, if your component is an STA component (and it seems like it is) and you can't change it to be a multi-threaded apartment component (MTA) or even better, free-threaded (so there is no marshaling between apartments at all) because a) it was written in VB6, or b) it's a third-party dll, then you might be better off working with some sort of queue model.

Basically, have all of your other work run asynchronously, then have a thread (or process, it's up to you), that will consume requests to call this component one at a time, as fast as it can (mind you, you can instantiate multiple instances of this component in multiple threads, you just have to make sure you set the ApartmentState property on the Thread class to ApartmentState.STA) and then publish events/callbacks when the call is complete and continue your other work asynchronously.

It's basically like having two producer/consumer implementations, one to dispatch the calls to the COM component, and another to dispatch the results when done.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...