致开

STA in COM

COM now has five types of Apartment:
1. Legacy
2. STA
3. Free
4. Both
5. Neutral

I'll discuss the Apartment in this article.

COM Objects living in Apartment will be protected by COM, any other calls for this object will be serialized by the COM. If there are concurrent threading in your application and you also don't want to the complicated multi-thread concurrency, you may get to love the Apartment model.

Here are some points of the Apartment modle:
1. Each Single Apartment only contains one thread.
2. Each thread should call ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); to join the STA.
3. If  you want to call the STA COM object living in other STA, you need to marshal your pointer.
4. Each STA may contain more than one COM objects.
5. At one time a STA allows only one thread running.

The code for COM object is simple. Here is I just list the code snippet for the client.
#include <iostream>
using namespace std;

#import 
"CarDemo.dll" no_namespace



void ThreadFunc(void *);
//IFreeCar * pCar;
//IFreeCar * pCar;
ICar * pCar;
int _tmain(int argc, _TCHAR* argv[])
{
    ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
    {
        ICar 
* pCar;
        ::CoCreateInstance(__uuidof(Car) , NULL, CLSCTX_INPROC_SERVER  , __uuidof(ICar) , (
void**)&pCar);
        IStream
* interfaceStream1;
        IStream
* interfaceStream2;
        CoMarshalInterThreadInterfaceInStream(__uuidof(ICar), pCar, 
&interfaceStream1);
        CoMarshalInterThreadInterfaceInStream(__uuidof(ICar), pCar, 
&interfaceStream2);
        HANDLE hThread[
2];
        hThread[
0= (HANDLE)::_beginthread(ThreadFunc, 0, (void*)interfaceStream1);
        hThread[
1= (HANDLE)::_beginthread(ThreadFunc, 0, (void*)interfaceStream2);
        ::WaitForMultipleObjects(
2, hThread, true, INFINITE);

        pCar
->Release();

    }
    
int iVal;
    cin
>>iVal;

    ::CoUninitialize();
    
return 0;
}

void ThreadFunc(LPVOID lpParameter)
{
    ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
    {
        IStream
* pStream = reinterpret_cast<IStream*>(lpParameter);
        ICar 
* pCar;
        CoGetInterfaceAndReleaseStream(pStream, __uuidof(ICar), reinterpret_cast
<void**>(&pCar));
        pCar
->Drive(3);
        pCar
->Release();
    }
    ::CoUninitialize();
}

Here is some helpful links for you to understand the STA better:
http://support.microsoft.com/default.aspx?scid=kb;en-us;172314
http://support.microsoft.com/kb/206076



posted on 2008-12-16 11:57 Xiaxi 阅读(268) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2008年12月>
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

导航

统计

常用链接

留言簿(1)

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜