我有一个ATL-COM组件使用的DLL。在我的DLL中,从FinalConstruct调用了StartMonitoring方法。我想在StartMonitoring()中创建后台线程,但是创建了线程并返回了有效的句柄,但线程内的代码从未执行过。这是否与ATL组件的工作方式有关?请原谅我,如果它是一个愚蠢的问题,但我对ATL / COM没有任何了解。
在这里,我认为它与COM的工作方式有关。在我的情况下,我需要StartMonitoring来启动后台线程,并且从FinalRelease()调用StopMonitoring时,将指示此后台线程退出,然后等待退出。现在,由于线程尚未启动但已提供有效的句柄,因此StopMonitoring将发出信号并永远等待。如果我通过绕过Wait强制结束StopMonitoring并返回到FinalRelease(),则MonitorThreadProc然后开始执行。
unsigned int WINAPI CMonitor::MonitorThreadProc(LPVOID lpvParam)
{
std::cout << "Enter MonitorThreadProc" << endl; //Never hits this
if (lpvParam == nullptr)
return 1;
CMonitor *pMonitor = static_cast<CMonitor*>(lpvParam);
return (unsigned int)pMonitor->Run();
}
void CMonitor::StopMonitoring()
{
if(m_EvtReg)
{
m_EvtStopMonitoring.Set();
DWORD dwResult = ::WaitForSingleObject(m_hThread, INFINITE);
if(dwResult == WAIT_OBJECT_0)
{
cout<<"Thread terminated"<<endl;
}
}
m_EvtReg.Close();
m_EvtStopMonitoring.Close();
HANDLE h = m_hThread.Detach();
CloseHandle(h);
}
bool CMonitor::StartMonitoring()
{
int num = 0;
unsigned int nThreadId = 0;
HANDLE hThread = (HANDLE)_beginthreadex(nullptr, 0, MonitorThreadProc, (LPVOID)this, 0, &nThreadId);
if(hThread == nullptr)
{
return false;
}
//I get a valid handle from _beginthreadex, but the thread never gets executed.
m_hThread.Attach(hThread);
return true;
}
答案 0 :(得分:0)
奇怪的行为是由于在DLL加载期间保持了加载程序锁定。在保持加载程序锁之前,线程从未被调度,因此我看不到代码执行。