两次调用 CoInitialize()
假设我的应用程序在启动时调用 CoInitialize,并在存在之前调用 CoUninitialize。
假设我有一个由我的应用程序使用的第三方组件并且执行类似的操作,这会导致某种失败吗?
当调用已经提交时,可以调用 CoInitialize 吗?第二次调用会失败吗?或者它只是“让它过去”,因为它已经被调用了。
Let's say my application calls CoInitialize when it starts and CoUninitialize before it exists.
Assuming I have a 3rd party component that's used by my application and does a similar thing, will this cause some kind of failure?
is it okay to call CoInitialize when that call has already been submitted? will the second call fail? or will it just "let it pass" as it's already called.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果已在调用线程中初始化,
CoInitialize
将返回S_FALSE
。但是,对于返回S_OK
和S_FALSE
的调用,都需要进行CoUninitialize
调用。对该函数的调用次数会被统计,并且只有当 CoUninitialize 的次数等于 CoInitialize 的次数时,它才会真正取消初始化。所以总而言之,第二次调用是无害的,多次调用这对函数也没有问题。
CoInitialize
will returnS_FALSE
if it has already been initialized in the calling thread. However, for both invocations that returnS_OK
andS_FALSE
there needs to be aCoUninitialize
call. The number of calls to this functions get counted, and only when the number ofCoUninitialize
equals that ofCoInitialize
it will actually uninitialize things.So in conclusion, a second call is harmless, and there are no problems with calling this pair of functions more than once.
这是根本错误的,CoInitialize() 必须由拥有线程的代码调用。如果它像进程内服务器一样运行并且不启动自己的线程,则它永远不是第 3 方组件。
当然,当它与公寓类型不一致时,这可能而且将会出错。这是它无法保证的,STA 是通常的选择,并且需要泵送消息循环。组件不会这样做,这是主机的工作。如果公寓类型不匹配,则需要封送接口指针。当它依赖于其选择的公寓类型时,它不会这样做。
It is pretty fundamentally wrong, CoInitialize() must be called by the code that owns the thread. Which is never the 3rd party component if it acts like an in-process server and doesn't start its own threads.
And sure, this can and will go wrong when it doesn't agree about the apartment type. Which is something it cannot guarantee, an STA is the usual choice and that requires pumping a message loop. The component won't do that, it's the host's job. And if the apartment type is a mismatch then it needs to marshal the interface pointer. Which it won't do when it relies on its apartment type of choice.