MFC 类内线程函数

线程函数必须是全局函数或静态成员函数。

非静态成员函数都有一个隐含的参数用于接收所属类的this指针,一般情况下调用时参数不匹配。所以static可以干掉隐含的参数

但是没有了this,类内的函数就无法调用了。所以AfxBeginThread(线程函数,(LPVOID)this),this又回来了,这样可以调用啦。

CWinThread* AFXAPI AfxBeginThread(
AFX_THREADPROC pfnThreadProc, //线程的入口函数,声明一定要如下: UINT MyThreadFunction( LPVOID pParam );
LPVOID pParam,                                 //线程参数
int nPriority,
UINT nStackSize,
DWORD dwCreateFlags,
LPSECURITY_ATTRIBUTES lpSecurityAttrs)

【案例】

//头文件中声明 static UINT MyThreadFunction(LPVOID pParam);//定义线程入口函数
UINT CMFCApplication25Dlg::MyThreadFunction(LPVOID pParam)//线程入口函数,具体实现
{
    CMFCApplication25Dlg* dlg = (CMFCApplication25Dlg*)pParam;//this赋给dlg
    for (int i = 0; i <= 100; i++)
    {
        dlg->SetDlgItemInt(IDC_STATIC, i, false);//通过类的对象来操作
        Sleep(100);
    }
    return 0;
}

void CMFCApplication25Dlg::OnBnClickedButton1()
{
    // TODO:  在此添加控件通知处理程序代码
    AfxBeginThread(MyThreadFunction, (LPVOID)this);//this赋给线程入口函数的参数pParam
}

【参考】

https://blog.csdn.net/MissXy_/article/details/80330263

posted @ 2019-11-28 11:27  夕西行  阅读(1133)  评论(0编辑  收藏  举报