在我的应用程序中,我有一个模态对话框,其中包含大约 20 个不同的组合框,这些组合框绑定(bind)到数据库中的某些字段。数据库很大,在加载对话框时,我必须从数据库中加载所有组合框。所以我设置了 20 个线程(每个组合框各 1 个)。
一切正常,但仅当用户在线程运行时使用关闭或取消按钮或确定按钮关闭对话框时才会出现问题;在这种情况下,应用程序会崩溃。
我也曾尝试过早终止线程,但这无济于事。这是线程终止代码
if(m_iNoOfThreadsCompleted != m_iTotalThreads)
{
for(int i = 0; i < m_iTotalThreads - 1; i++)
{
if (m_threads[i] != NULL)
{
GetExitCodeThread(m_threads[i]->m_hThread, &exit_code);
if(exit_code == STILL_ACTIVE)
CloseHandle(m_threads[i]->m_hThread);
}
if(m_iNoOfThreadsCompleted == m_iTotalThreads)
break;
}
}
问题是什么?还是我需要使用更好的方法?
最佳答案
同步线程通常使用事件来完成。
// Before Creating threads
HANDLE hEndEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
// Pass handle to threads
然后在终止
SetEvent(hEndEvent);
WaitForMultipleObjects(m_iTotalThreads,m_threads,TRUE,INFINITE); // Wait for all threads to end
// Loop through and close all the thread handles
请注意,您需要偶尔寻找要设置的结束事件,否则您的线程将不会结束。
// In Thread
if (WaitForSingleObject(hEndEvent,0)==WAIT_OBJECT_0) {
// Clean up
return 0;
}
关于c++ - 应用程序在线程运行时关闭对话时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11876876/