I have written a com component in .NET and if I try to take a lock on any object in any method (that is invoked by unmanaged code talking to my com component) I get an exception.
I do not have the exact text of the exception at this moment but it wasn’t much helpful either.
So my question is under what circumstances a lock(syncObject) would throw an exception?
Here are some facts:
- syncObject is not null
- syncObject is not already locked
Would it have anything to do with callee running in STA (Single Threaded Apartment) or MTA (Multi Threaded Apartment)?
From this page:
So as you can read, it seems that under resource constrained conditions we might get exceptions thrown from the Enter method of Monitor which lock(o) uses internally.
So perhaps your solution is something like a spin-wait?
Where cond could be some
used with e.g. Interlocked.CompareExchange where you change to e.g. Thread.Current.ManagedThreadID or something else non-zero?