Re: CoInitialize/CoUninitialize
"Alf P. Steinbach" <alfps@start.no> wrote in message
news:3qednWbwtcR8IvXVnZ2dnUVZ_ojinZ2d@posted.comnet
Here is bad code, relying on local COM initialization:
void doAnHTMLDialog()
{
if( !SUCCEEDED( CoInitialize() ) )
{
throwX( "Unable to initalize COM" );
}
// Do HTML dialog using COM-based IE machinery, then
CoUninitialize();
// Dontcha know, there might still be some thread using COM!
Splat! }
CoInitialize/CoUninitialize are per thread. Calling CoUninitialize in
one thread cannot affect other threads.
While I agree it's not the best idea, I don't see the horrible problems
in the code above you seem to ascribe to it. The code should work as
written.
Here is less bad code, which might even be counted as good if one
ignores exception safety aspects and lack of abstraction and
reusability:
void doAnHTMLDialog()
{
HRESULT const initResult = CoInitialize();
if( FAILED( initResult ) )
{
throwX( "Unable to initalize COM" );
}
else if( initResult != S_OK )
{
CoUninitialize();
throwX( "COM was not initialized before calling
doAnHTMLDialog." ); }
CoUninitialize(); // "Undo" the checking call of
CoInitialize.
// Do HTML dialog using COM-based IE machinery.
}
If you are willing to do the complete CoInitialize / CoUninitialize
dance just for checking, why not do it for real as in the first example,
and actually use the freshly initialized apartment (since you have
already invoked the overhead anyway)?
--
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