使用用户界面线程
创建一个用户界面线程比一个工作者线程复杂的多:前者必须要从CWinThread派生一个类,并重载一些成员函数。调用AfxBeginThread开始一个用户界面线程与开始一个工作者线程很相似,只是工作者线程的控制函数和参数被指向CWinThread导出类的对象的指针多代替。此时,AfxBeginThread调用之后也不再运行控制函数,而是调用线程对性的InitInstance函数。
具体步骤:
(1)从CWinThread派生一个线程类,重载成员函数:
- InitInstanc 必须重载。而且在类的声明和实现中必须使用DECLARE_DYNCREATE和IMPLEMENT_DYNCREATE宏。
- CWinThread的其他几个函数可以根据需要选择是否重载。
- 在CWinThread的Run成员函数中,会获取线程的窗口消息,它将这些消息送给PreTranslateMessage处理。可以重载这个函数,将在这些消息通过MFC的标准消息路线发送。
- CWinThread的数据成员,包含:线程ID、线程句柄以及指向程序的主窗口的指针。其中M_bAtoDelete成员决定线程结束时对象是否被删除。
- 利用CWinThread的SuspendThread和ResumeThread函数可以从外部控制线程。SuspendThread使线程的挂起次数增加,而ResumeThread则使之减少。如果线程的挂起次数不为0,操作系统将不对其进行调度。二者应该配对使用。
Base Class Members
Data Members
m_bAutoDelete | Specifies whether to destroy the object at thread termination. |
m_hThread | Handle to the current thread. |
m_nThreadID | ID of the current thread. |
m_pActiveWnd | Pointer to the main window of the container application when an OLE server is in-place active. |
m_pMainWnd | Holds a pointer to the application's main window. |
Construction
CreateThread | Starts execution of a CWinThread object. |
CWinThread | Constructs a CWinThread object. |
Operations
GetMainWnd | Retrieves a pointer to the main window for the thread. |
GetThreadPriority | Gets the priority of the current thread. |
PostThreadMessage | Posts a message to another CWinThread object. |
ResumeThread | Decrements a thread's suspend count. |
SetThreadPriority | Sets the priority of the current thread. |
SuspendThread | Increments a thread's suspend count. |
Overridables
ExitInstance | Override to clean up when your thread terminates. |
InitInstance | Override to perform thread instance initialization. |
IsIdleMessage | Checks for special messages. |
OnIdle | Override to perform thread-specific idle-time processing. |
PreTranslateMessage | Filters messages before they are dispatched to the Windows functions TranslateMessage and DispatchMessage. |
ProcessMessageFilter | Intercepts certain messages before they reach the application. |
ProcessWndProcException | Intercepts all unhandled exceptions thrown by the thread's message and command handlers. |
PumpMessage | Contains the thread's message loop. |
Run | Controlling function for threads with a message pump. Override to customize the default message loop. |
Operators
operator HANDLE | Retrieves the handle of the CWinThread object.
|
(2)调用AfxBeginThread函数:
CWinThread *AfxBeginThread(
CRuntimeClass* pThreadClass,
int nPriority = THREAD_PRIORITY_NORMAL,
UINT nStackSize = 0,
DWORD dwCreateFlags = 0,
LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL
);
注:pThreadClass它指向一个CRuntimeClass对象,该对象由RUNTIME_CLASS宏从CWinThread的派生类创建。