在做多线程的时候出现的错误,其实问题是出在别的地方。下面时出现的断言错误的地方
原错误代码:
//绘制绿球
if (m_Isgreenball)
{
CDC *pDC = m_greenrect.GetDC();
CBrush *poldbrush;
CBrush newbrush(RGB(0,255,0));
poldbrush=pDC->SelectObject(&newbrush);
pDC->Ellipse(greenball.pos,0,greenball.pos+greenball.rect.Height(),greenball.rect.Height());
pDC->SelectObject(poldbrush);
pDC->DeleteDC();
}
断言错误的地方:
void CHandleMap::RemoveHandle(HANDLE h)
{
// make sure the handle entry is consistent before deleting
CObject* pTemp = LookupTemporary(h);
if (pTemp != NULL)
{
// temporary objects must have correct handle values
HANDLE* ph = (HANDLE*)((BYTE*)pTemp + m_nOffset); // after CObject
ASSERT(ph[0] == h || ph[0] == NULL);
if (m_nHandles == 2)
ASSERT(ph[1] == h); // 报错定位此处
}
pTemp = LookupPermanent(h);
if (pTemp != NULL)
{
HANDLE* ph = (HANDLE*)((BYTE*)pTemp + m_nOffset); // after CObject
ASSERT(ph[0] == h);
// permanent object may have secondary handles that are different
}
// remove only from permanent map -- temporary objects are removed
// at idle in CHandleMap::DeleteTemp, always!
m_permanentMap.RemoveKey((LPVOID)h);
}
#endif
后来查书发现是句柄释放错了,多多感谢孙鑫老师。
用GetDC()得到的DC, 必须调用ReleaseDC()
用CreateDC()创建的DC, 必须调用DeleteDC()
区别:
ReleaseDC()仅是释放对DC的引用
DeleteDC()是删除DC对象, 使用GetDC()的时候, 明显的这个DC不是我们自己创建的, 使用DeleteDC()的话就会将别人(通常是MFC框架)创建的DC干掉, 这样当别人要使用自己创建的DC时, 就会产生异常 了.
ReleaseDC()恰好解决这个问题, 它仅是释放一个引用, 告诉创建者DC, 我已经不用了.
下面是修改后的代码:
//绘制绿球
if (m_Isgreenball)
{
CDC *pDC = m_greenrect.GetDC();
CBrush *poldbrush;
CBrush newbrush(RGB(0,255,0));
poldbrush=pDC->SelectObject(&newbrush);
pDC->Ellipse(greenball.pos,0,greenball.pos+greenball.rect.Height(),greenball.rect.Height());
pDC->SelectObject(poldbrush);
ReleaseDC(pDC);
}