本人为新手,编写了一个线程测试程序。当在调试状态下运行,每运行到showInfo()中的UpdateData(FALSE)时就会引发debug assertion failed对话框的出现。而在发布状态下则没有这个问题。程序包含以下主要内容:
class CThread //线程测试接口类
{
public:
void start();
virtual void run() = 0;
private:
static void entry(void *);
};
void CThread::start(){
_beginthread(entry,0,this);
}void CThread::entry(void * pThread){
((CThread *)pThread)->run();
}
class CStep1Dlg;
class CThtest: public CThread{ //线程接口具体实现类
public:
void run();
void setOut(CStep1Dlg*);//设置输出对话框
~CThtest(){
m_dlgOut=NULL;
}
private:
CStep1Dlg* m_dlgOut;//指向输出对话框的指针
};
class CStep1Dlg : public CDialog//测试输出对话框
{
// Construction
public:
CStep1Dlg(CWnd* pParent = NULL); // standard constructor
void showInfo(CString);//显示信息,用于回调
// Dialog Data
//{{AFX_DATA(CStep1Dlg)
enum { IDD = IDD_STEP1_DIALOG };
CString m_edit; //编辑控件关联变量
//}}AFX_DATA
afx_msg void OnStart();//启动线程....
private:
CThtest m_thread;
};
void CThtest::setOut(CStep1Dlg* pout){
m_dlgOut = pout;
}
void CThtest::run(){
m_dlgOut->showInfo("I,m run!\r\n");//显示线程运行状态
}
BOOL CStep1Dlg::OnInitDialog()
{
CDialog::OnInitDialog();
...
m_thread.setOut(this);//设置输出
return TRUE; // return TRUE unless you set the focus to a control
}
void CStep1Dlg::OnStart()
{
m_thread.start(); //启动线程
}void CStep1Dlg::showInfo(CString str){ //显示
m_edit+=str;
UpdateData(FALSE);
}
class CThread //线程测试接口类
{
public:
void start();
virtual void run() = 0;
private:
static void entry(void *);
};
void CThread::start(){
_beginthread(entry,0,this);
}void CThread::entry(void * pThread){
((CThread *)pThread)->run();
}
class CStep1Dlg;
class CThtest: public CThread{ //线程接口具体实现类
public:
void run();
void setOut(CStep1Dlg*);//设置输出对话框
~CThtest(){
m_dlgOut=NULL;
}
private:
CStep1Dlg* m_dlgOut;//指向输出对话框的指针
};
class CStep1Dlg : public CDialog//测试输出对话框
{
// Construction
public:
CStep1Dlg(CWnd* pParent = NULL); // standard constructor
void showInfo(CString);//显示信息,用于回调
// Dialog Data
//{{AFX_DATA(CStep1Dlg)
enum { IDD = IDD_STEP1_DIALOG };
CString m_edit; //编辑控件关联变量
//}}AFX_DATA
afx_msg void OnStart();//启动线程....
private:
CThtest m_thread;
};
void CThtest::setOut(CStep1Dlg* pout){
m_dlgOut = pout;
}
void CThtest::run(){
m_dlgOut->showInfo("I,m run!\r\n");//显示线程运行状态
}
BOOL CStep1Dlg::OnInitDialog()
{
CDialog::OnInitDialog();
...
m_thread.setOut(this);//设置输出
return TRUE; // return TRUE unless you set the focus to a control
}
void CStep1Dlg::OnStart()
{
m_thread.start(); //启动线程
}void CStep1Dlg::showInfo(CString str){ //显示
m_edit+=str;
UpdateData(FALSE);
}
一般一个比较正确的程序在调试模式下与发布模式下执行的效果是一样的,都不出现debug assertion failed
2.CStep1Dlg::OnStart() 函数是在哪里调用的?一定要保证m_dlgOut所指向的对话框在线程生命期内不被消毁,否则窗口无效就会引发ASSERT(::IsWindow(m_hWnd))断言。
3.m_dlgOut所指向的对话框属于界面线程,与CThtest处于不同线程,所以要注意线程同步。