Question

I am working on a bug that related to an unmanaged MTA COM object. The object has Lock and Unlock methods and uses a mutex that requires the same thread that called Lock to call Unlock.

The problem is that when Lock and Unlock are called from a managed STA thread (using COM interop), the calls come into the COM object on a RPC callback thread but the callback thread that is used is not always the same for both calls. When it is not the same, the Unlock call fails because it can't unlock the mutex.

In other words:

Managed STA thread 1 -> RPC callback (thread 11) -> Lock

Managed STA thread 1 -> RPC callback (thread 12) -> Unlock -> Error

I am trying to evaluate all possible solutions before making any decisions on a fix. As such, I am trying to find out:

1) Is there is a way to prevent a RPC callback thread from being used in the first place? In my testing, if I make the calls to the object from an unmanaged STA thread, the calls seem to come in on the calling thread itself. What is different when the call is coming from .Net that necessitates the use of an RPC callback thread? Is there any way to prevent RPC callbacks from being used? (except for using an MTA calling thread)

2) If not, is there a way to force a consistent RPC callback thread to be used from the same managed STA thread?

Was it helpful?

Solution

This is by design for a free-threaded server. COM takes your word for it and allows stubs to use arbitrary RPC threads. You cannot make any assumptions about the thread identity, the RPC thread is picked from a pool and is recycled. Unfortunately it often picks the same one when the calls are sequenced so it will look like it works fine at first. But trouble starts as soon as more than one concurrent server call is made. There is no option to make it selective, a free-threaded server promises to not care. Nor could that work well in practice, it would either scale horribly or induce deadlock.

You therefore cannot use a mutex to implement locking, it has thread affinity. A semaphore is a good choice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top