From : http://blog.csdn.net/zj510/article/details/39008107
那么如果在STA套间里面创建MTA对象,又如何?
看这段代码:
- // TestCom.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <atlbase.h>
- #include <atlcom.h>
- #include "../MyCOM/MyCOM_i.h"
- #include "../MyCOM/MyCOM_i.c"
- #include <iostream>
- #include <thread>
- using namespace std;
- void WorkThread()
- {
- CoInitialize(0);
- WCHAR temp[100] = { 0 };
- swprintf_s(temp, L"thread tid: %d\n", ::GetCurrentThreadId());
- ::OutputDebugStringW(temp);
- {
- CComPtr<IMyRect> spRect;
- HRESULT hr = spRect.CoCreateInstance(CLSID_MyRect, NULL, CLSCTX_INPROC_SERVER);
- hr = spRect->Draw(CComBSTR(L"red"));
- }
- CoUninitialize();
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- CoInitialize(0);
- WCHAR temp[100] = {0};
- swprintf_s(temp, L"main tid: %d\n", ::GetCurrentThreadId());
- ::OutputDebugStringW(temp);
- {
- CComPtr<IMyRect> spRect;
- spRect.CoCreateInstance(CLSID_MyRect, NULL, CLSCTX_INPROC_SERVER);
- spRect->Draw(CComBSTR(L"red"));
- CComPtr<IMyRect> spRect2;
- spRect2.CoCreateInstance(CLSID_MyRect, NULL, CLSCTX_INPROC_SERVER);
- spRect2->Draw(CComBSTR(L"blue"));
- }
- std::thread t(WorkThread);
- std::thread t1(WorkThread);
- std::thread t2(WorkThread);
- CoUninitialize();
- t.join();
- t1.join();
- t2.join();
- return 0;
- }
// TestCom.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <atlbase.h>
#include <atlcom.h>
#include "../MyCOM/MyCOM_i.h"
#include "../MyCOM/MyCOM_i.c"
#include <iostream>
#include <thread>
using namespace std;
void WorkThread()
{
CoInitialize(0);
WCHAR temp[100] = { 0 };
swprintf_s(temp, L"thread tid: %d\n", ::GetCurrentThreadId());
::OutputDebugStringW(temp);
{
CComPtr<IMyRect> spRect;
HRESULT hr = spRect.CoCreateInstance(CLSID_MyRect, NULL, CLSCTX_INPROC_SERVER);
hr = spRect->Draw(CComBSTR(L"red"));
}
CoUninitialize();
}
int _tmain(int argc, _TCHAR* argv[])
{
CoInitialize(0);
WCHAR temp[100] = {0};
swprintf_s(temp, L"main tid: %d\n", ::GetCurrentThreadId());
::OutputDebugStringW(temp);
{
CComPtr<IMyRect> spRect;
spRect.CoCreateInstance(CLSID_MyRect, NULL, CLSCTX_INPROC_SERVER);
spRect->Draw(CComBSTR(L"red"));
CComPtr<IMyRect> spRect2;
spRect2.CoCreateInstance(CLSID_MyRect, NULL, CLSCTX_INPROC_SERVER);
spRect2->Draw(CComBSTR(L"blue"));
}
std::thread t(WorkThread);
std::thread t1(WorkThread);
std::thread t2(WorkThread);
CoUninitialize();
t.join();
t1.join();
t2.join();
return 0;
}
IMyRect是一个MTA接口。上面的代码运行结果如下:
红色部分是主线程输出的,主线程初始化STA套间,主线程id是7812,然后COM函数里面输出的是4936.那么说明COM并不是在主线程里面运行的。
绿色部分是3个辅助线程输出的,可以看到COM运行线程中,其中2个是一样的,另外一个不一样。
这就说明:
1. 当在STA套间里面创建MTA对象时,系统会自动创建一个MTA套间。
2. MTA对象在MTA套间里面运行。
3. 运行线程由系统来创建,系统会创建几个运行线程,并且挑选某个线程为当前调用服务。
相关资料:
http://support.microsoft.com/kb/150777
http://forums.codeguru.com/showthread.php?449647-STA-component-call-MTA-component