AfxBeginThread usage for creating a Mfc Worker Thread


A worker thread in MFC is used for many background tasks like printing, computations, network servers etc.,  Unlike User Interface threads, worker threads do not have their own Message Maps.

A worker thread in an MFC program can be implemented with a simple controlling function of the following declaration type.

 UINT Controlling_function_name(void parameter);

AfxBeginThread:

Worker threads are created by calling the function AfxBeginThread. This function has two signatures. One for creating user interface threads and the other for creating a worker thread. The AfxBeginThread for worker thread takes the function name as the first parameter. The function passed as a parameter to the AfxBeginThread function will then be used for running as a separate thread.

MFC Worker Thread Sample – AfxBeginThread:

This article explains the worker thread with a Dialog based application.

  1. Start by creating a MFC Dialog based application with name as WorkerThread.
  2. After generating the necessary files, open the WorkerThreadDlg.cpp and copy/paste the following code.UINT WorkerThreadProc( LPVOID Param )
    	//Sample function
    	for using in AfxBeginThread
    	{
    		CFile file;
    		file.Open("C:\Temp\test.txt",CFile::modeCreate|CFile::modeWrite);
    		CString strValue;
    		for(int i=0;i<=100;i++)
    		{
    
    		strValue.Format("Value:%d",i);
    
    		file.Write(strValue,strValue.GetLength());
    		// Write to the file for worker thread using
    		AfxBeginThread
    		}
    		file.Close();
    
    		return TRUE;
    	}
  3. In one of the dialog commands, call the AfxBeginThread as follows. For the sake of simplicity this article uses it in the OnOK function.
    	void CWorkerThreadDlg::OnOK()
    	{
    		// TODO: Add extra validation here
    		AfxBeginThread(WorkerThreadProc,NULL,THREAD_PRIORITY_NORMAL,0,0,NULL);
    		MessageBox("Thread Started");
    	}
  4. Now Build and run the application. If the OK button is clicked, it will write the data into a file.

Actually speaking this sample does not truly use a multi-threaded situation. But still it tries to explain how the AfxBeginThread can be used to create a worker thread.

The sample code explains how to create a worker thread with the above code samples.