分别用
AfxBeginThread函数和CreateThread函数创建线程
方法一 使用
AfxBeginThread创建线程
1、在对话框类中添加静态线程函数,如:
-
class CGenerateCSVDlg : public CDialog
-
{
-
public:
-
CGenerateCSVDlg (CWnd* pParent = NULL);
-
static UINT CreateCheckDatabaseThread(LPVOID);//创建线程函数
-
CWinThread *DatabaseThread;
-
BOOL RunCheckDatabaseThread();//线程调用函数
-
//{{AFX_DATA(CGenerateCSVDlg )
-
enum { IDD = IDD_CHECKSERVER_DIALOG };
-
//}}AFX_DATA
-
//{{AFX_VIRTUAL(CGenerateCSVDlg )
-
protected:
-
//{{AFX_VIRTUAL(CGenerateCSVDlg )
-
virtual void DoDataExchangeCDataExchange*pDX);
-
//}}AFX_VIRTUAL
-
//{{AFX_MSG(CGenerateCSVDlg )
-
//}}AFX_MSG
-
DECLARE_MESSAGE_MAP()
-
};
2、在
CGenerateCSVDlg .cpp文件中添加如下函数:
-
UINT CGenerateCSVDlg ::CreateCheckDatabaseThread(LPVOID phread)
-
{
-
CGenerateCSVDlg *p=(CGenerateCSVDlg *)phread;
-
while (TRUE)
-
{
-
Sleep(3000);
-
p->RunCheckDatabaseThread();
-
}
-
return TRUE;
-
}
-
BOOL CGenerateCSVDlg ::RunCheckDatabaseThread()
-
{
-
return TRUE;
-
}
3、创建线程
-
BOOL CGenerateCSVDlg ::OnInitDialog()
-
{
-
CDialog::OnInitDialog();
-
DatabaseThread=::AfxBeginThread(CreateCheckDatabaseThread,this,THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED);
-
DatabaseThread->ResumeThread();
-
return TRUE; // return TRUE unless you set the focus to a control
-
}
方法二 使用
CreateThread创建线程
1、定义一个全局函数,不包含在类中,如:
-
DWORD WINAPI ThreadRun(LPVOID lpParamter)
-
{
-
CGenerateCSVDlg *p=(CGenerateCSVDlg *)lpParamter;
-
while(p->IsRunThrend) //IsRunThrend为CGenerateCSVDlg类中的成员变量
-
{
-
if (p->IsCreateCSV) //IsCreateCSV为CGenerateCSVDlg类中的成员变量
-
{
-
p->CreateCSV(); //CreateCSV为CGenerateCSVDlg类中的成员函数
-
}
-
}
-
return 0;
-
}
2、
在CGenerateCSVDlg .cpp文件中添加如下函数:
-
void CGenerateCSVDlg::CreateCSV()
-
{
-
-
}
3、创建线程函数,如下:
-
BOOL CGenerateCSVDlg ::OnInitDialog()
-
{
-
CDialog::OnInitDialog();
-
HANDLE hThread = CreateThread(NULL, 0, ThreadRun, (LPVOID)this, 0, NULL);
-
CloseHandle(hThread);
-
return TRUE; // return TRUE unless you set the focus to a control
-
}
4、类中的成员
-
class CGenerateCSVDlg : public CDialog
-
{
-
public:
-
CGenerateCSVDlg (CWnd* pParent = NULL);
-
void CreateCSV();
-
BOOL IsCreateCSV;
-
BOOL IsRunThrend;
-
//{{AFX_DATA(CGenerateCSVDlg )
-
enum { IDD = IDD_CHECKSERVER_DIALOG };
-
//}}AFX_DATA
-
//{{AFX_VIRTUAL(CGenerateCSVDlg )
-
protected:
-
//{{AFX_VIRTUAL(CGenerateCSVDlg )
-
virtual void DoDataExchangeCDataExchange*pDX);
-
//}}AFX_VIRTUAL
-
//{{AFX_MSG(CGenerateCSVDlg )
-
//}}AFX_MSG
-
DECLARE_MESSAGE_MAP()
-
};
阅读(3230) | 评论(0) | 转发(0) |