Re: re-entrancy pattern issue setbacks
"George" <George@discussions.microsoft.com> wrote in message
news:4E7B5364-665C-4490-959A-628CA63B8526@microsoft.com
Two questions about re-entrancy issue,
http://www.codeproject.com/KB/COM/sta_issues.aspx
1. What is the setback of the issue? I think it is still thread-safe
since only one STA owning thread will execute on STA component;
The problem is that it violates most people's assumptions. When you call
a method, you don't expect any other code to run until the method
returns.
Consider:
void MyMethod() {
BeginModifyingDataStructure();
pObj->RemoteCOMCall();
EndModifyingDataStructure();
}
You make some changes to an internal data structure, then make a COM
call, then finish your modifications. After this last step, the
structure is in a consistent and usable state. But in the middle, it may
be inconsistent, its invariants violated. Normally, this would not be a
problem - you will restore the invariants before MyMethod returns, and
all other code dealing with this data structure will be happy. But with
reentrancy, some code (even MyMethod itself) may run while the data
structure is halfway through a modification. Most likely, the code
doesn't expect this and would break in interesting ways.
Or consider:
class C {
vector<int> v;
void MyMethod() {
if (!v.empty()) {
pObj->RemoteCOMCall();
v[0] = 42;
}
}
};
This code assumes that if v was not empty before the call, it remains
unchanged afterwards. But some code might have run reentrantly from
inside RemoteCOMCall and modified v.
2. How to avoid it in design?
You can make your code reentrant. This means making sure that all
invariants are restored before making a cross-apartment COM call, and
not expecting data structures to remain unchanged afterwards.
Or, you can implement IMessageFilter and actively prevent reentrancy, by
rejecting incoming COM calls and perhaps some window messages (e.g. user
input that may trigger further processing when you are not ready for
it).
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925