MFC 创建UI线程

来源:互联网 发布:淘宝免费模板代码 编辑:程序博客网 时间:2024/04/29 12:35

对于windows来说,所有的线程都是一样的,但MFC却把线程区分为两种:用户界面(UI)线程和工作者线程。用户界面线程具有消息循环而工作者线程没有。UI线程可以创建窗口并给这些窗口发送消息,工作者线程执行后台任务,因其不接受用户直接输入蘑菇不需要窗口和消息循环。

创建UI线程需要首先从CWinThread派生一个线程类,改类与CWinApp类派生额应用程序类很相似(CwinApp继承自CWinThread)。派生类必须重载InitInstance,在其中创建一个对话框。关于对话框的创建可以参见上博文MFC中的模态对话框与非模态对话框.

首先在MFC类向导中添加继承自CWinThread的一个线程类CUIThread


重载InitInstance如下(此处创建模态对话框):

BOOL CUIThread::InitInstance(){// TODO: 在此执行任意逐线程初始化MyDialog mydlg;m_pMainWnd = &mydlg;mydlg.DoModal();return TRUE;}

其中m_pMainWnd= &mydlg;是指定线程主窗口,m_pMainWnd的作用MSDN的解释如下:

The Microsoft Foundation Class Library will automaticallyterminate your thread when the window referred to by m_pMainWnd isclosed. If this thread is the primary thread for an application, theapplication will also be terminated. If this data member is NULL,the main window for the application's CWinApp object will beused to determine when to terminate the thread. m_pMainWnd isa public variable of type CWnd*.

Typically, you set this member variable when you override InitInstance.In a worker thread, the value of this data member is inherited from its parentthread.

也就是说当和m_pMainWnd相关的窗口被关闭后,MFC会自动终止你的线程。
接着在主对话框中添加按钮响应函数用于调用AfxBeginThread

void CModalUIDlg::OnBnClickedOk(){// TODO: 在此添加控件通知处理程序代码//CDialogEx::OnOK();CWinThread* pThread=AfxBeginThread(RUNTIME_CLASS(CUIThread));}

函数AfxBeginThread可用于创建工作者线程和UI线程,他们的调用方式不同,对于工作者线程:

CWinThread* AfxBeginThread(AFX_THREADPROC pfnThreadProc,//线程回调函数LPVOID pParam,     //传递给回调函数的参数int nPriority = THREAD_PRIORITY_NORMAL,//线程优先级 UINT nStackSize = 0,//指定堆栈大小DWORD dwCreateFlags = 0,//创建表示(CREATE_SUSPENDED:挂起,0:立即执行)LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL //安全属性);
对于UI线程:

CWinThread* AfxBeginThread(CRuntimeClass* pThreadClass,//CWinThread派生的RUNTIME_CLASS类int nPriority = THREAD_PRIORITY_NORMAL,//线程优先级 UINT nStackSize = 0,//指定堆栈大小DWORD dwCreateFlags = 0,//创建表示(CREATE_SUSPENDED:挂起,0:立即执行)LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL //安全属性);

对应于之前讨论的模态与非模态对话框,这里也分别实现使用UI线程创建者两类对话框。

源码下载



参考:

[1]http://blog.csdn.net/cbnotes/article/details/8465212

[2]https://msdn.microsoft.com/en-us/library/f3ddxzww.aspx









0 0