描述:
Free,多线程 模式
创建线程,创建一个消息处理窗口,从线程里往窗口发送消息,窗口无没收到消息,这是什么回事,应该什么解决?
如果改用Apartment 模式就可以正常接收消息了,但我必须便用Free模式。
窗口是ATL的class CMyWindow :public CWindowImpl<CMyWindow, CWindow, CNullTraits>
创建线程和窗口:
STDMETHODIMP CCCCTest::Init(void)
{
mEventWindow = new CMyWindow(this);
mEventHwnd = mEventWindow->CreateWindows();
// TODO: Add your implementation code here
mHadle = CreateThread(
NULL, // default security attributes
0, // use default stack size
MyThreadFunction, // thread function name
this, // argument to thread function
0, // use default creation flags
&mThreadID); // returns the thread identifier
return S_OK;
}
线程内容
DWORD WINAPI MyThreadFunction( LPVOID lpParam )
{
CCCCTest* pTest = (CCCCTest*)lpParam;
DWORD dwTS = GetTickCount();
CoInitializeEx( NULL, COINIT_MULTITHREADED);
while (!pTest->mExit)
{
Sleep(5000);
if(pTest->mEventHwnd)
{
dwTS = GetTickCount();
MessageBox(NULL,L"PostMessage",L"MyThreadFunction",MB_OK);
if (!::PostMessage(pTest->mEventHwnd, WM_CALLBACK, (WPARAM)dwTS, 0))
{
}
}
}
CoUninitialize();
return 0;
}
如果有兴趣了解这个问题的,留下邮箱,我把整个测试代码发过去
解决方案1:
内部你不需要处理,消息循环本身却是线程相关的。
你必须在建立的窗口的线程中有消息循环才行。
如果你不用apartment,估计开发的难度比较大。 解决方案2:
需要建立消息循环。
解决方案3: 添加了一些测试代码
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(AppDomain.GetCurrentThreadId().ToString() );//添加
client = new CCCLib.CCCTest();
client.Init();
client.registerSuccess += new CCCLib._ICCCTestEvents_registerSuccessEventHandler(registerSuccess);
//thThread = new Thread(new ThreadStart(DoThreadEx));
//mExit = false;
//thThread.Start();
}
DWORD WINAPI MyThreadFunction( LPVOID lpParam )
{
TCHAR buff[10];
_itow(::GetCurrentThreadId(),buff,10);
MessageBox(NULL,buff,TEXT("wnd"),MB_OK);
CCCCTest* pTest = (CCCCTest*)lpParam;
DWORD dwTS = GetTickCount();
////////////////////////////////////////////////
STDMETHODIMP CCCCTest::Init(void)
{
mEventWindow = new CMyWindow(this);
mEventHwnd = mEventWindow->CreateWindows();
TCHAR buff[10];
_itow(mEventWindow->GetWindowThreadID(),buff,10);
MessageBox(NULL,buff,TEXT("wnd"),MB_OK);
// TODO: Add your implementation code here
mHadle = CreateThread(
NULL, // default security attribute
结论创建com对象的线程没有消息循环。
在APARTMENT模型下C#的创建的窗口的线程和创建com对象的线程是同一个线程,c#程序会提供消息循环,所以运行正常;
在free模型下,C#的创建的窗口的线程和创建com对象的线程和MyThreadFunction的线程都是不同的线程,所以说在MyThreadFunction的创建消息循环是没有效果的。