Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
702 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...