工作者线程:一般没有界面,处理后台耗时的操作。使用过程:1.定义线程函数 2.调用AfxBeginThread()函数,指定线程函数
用户界面线程:可以拥有自己的窗口界面,能够对用户的输入和事件做出相应。使用过程:1.定义一个CWinThread类的子类 2.调用AfxBeginThread()函数,指定线程类
1.创建MFC基于对话框的工程MFCThread,以后全部默认
2.增加UI对话框:在资源视图下,右击->插入Dialog;在对话框上右击->添加类CThreadDlg,基类是CDialogEx,且选中自动化
3.添加MFC类CUIThread,基类是CWinThread,且选中自动化;其关键代码
#include "ThreadDlg.h" BOOL CUIThread::InitInstance() { CThreadDlg dlg; m_pMainWnd=&dlg; dlg.DoModal(); return TRUE; }
4.主对话框类的关键代码
void CMFCThreadDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST1, m_wndListBox); } BEGIN_MESSAGE_MAP(CMFCThreadDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON_WORK, &CMFCThreadDlg::OnBnClickedButtonWork) ON_BN_CLICKED(IDC_BUTTON_UI, &CMFCThreadDlg::OnBnClickedButtonUi) END_MESSAGE_MAP() UINT CMFCThreadDlg::WorkerThreadProc(LPVOID pParam) { CMFCThreadDlg* pThis=(CMFCThreadDlg*)pParam; for (int i=0;i<10;i++) { pThis->m_wndListBox.AddString(L"Hello worker!"); Sleep(100); } return 0; } void CMFCThreadDlg::OnBnClickedButtonWork() { //启动工作者线程 AfxBeginThread(WorkerThreadProc,this); } #include "UIThread.h" void CMFCThreadDlg::OnBnClickedButtonUi() { //启动用户界面线程 AfxBeginThread(RUNTIME_CLASS(CUIThread)); }