How To

How to Make an MFC Worker Thread

By eHow Computers Editor
Rate: (2 Ratings)

Threads are the objects that make multi-tasking possible. Threads, each corresponding to a "time slice" or separate state of the running program, create the illusion that multiple users can share a server application. The Microsoft Foundation Class Library encapsulates threads via the CWinThread class, which supports User and Worker threads that run in the background. In a few steps, you can make a simple program utilizing a Worker Thread.

Difficulty: Moderate
Instructions

Things You'll Need:

  • Microsoft Visual Studio IDE
  • Book on MFC, such as "Programming Windows with MFC" by Jeff Prosise
  1. Step 1

    Start Microsoft Visual Studio. Create a dialog-based MFC project by clicking "File" from the upper menu and then "New." After clicking the "Projects" tab, select "MFC AppWizard(exe)" and type "WThread" in the "Project name:" edit box. Click "OK." In the next wizard screen, select "Dialog based," then click "Finish" and "OK." The wizard generates a default dialog box and its associated source files.

  2. Step 2


    Make a function that will act as the Worker thread for this MFC tutorial. Open the WorkerThreadDlg.cpp file by expanding the "Source Files" folder in the left pane and double-clicking the file. Copy/paste the following source code at the end of the file:

    void ThreadProcess(LPVOID param) {

    CFile f;

    f.Open("proof.txt", CFile::modeCreate | CFile::modeWrite);

    CString str;

    for(int i=0; i<50; i++) {

    str.format("Num: %d", i);

    f.Write(str, str.GetLength());

    }

    f.Close();

    }

  3. Step 3


    Activate the Worker thread (the function in Step 2) in an event. For an event, use the click of the default dialog's "OK" button. Get back into design mode by pressing Ctrl+F4. Select the "OK" button and double-click it. Press "OK" when the "Add Member Function" box appears. Copy and paste the following code inside the braces of "CWorkerThreadDlg::OnOK()."

    AfxBeginThread(ThreadProcess, NULL, THREAD_PRIORITY_TIME_CRITICAL
    , 0, 0, NULL);

    MessageBox("Worker Thread Activated", NULL, NULL);

  4. Step 4

    Compile and run the application. When you click "OK," a message box will appear stating that the background Worker thread has executed. Go to the project directory and see the written text in "proof.txt."

Tips & Warnings
  • You can start threads without the "AfxBeginThread()" function by creating a CWinThread-derived object and calling the "CreateThread()" member function.
  • This article doesn't demonstrate multi-tasking because that would require the creation of more than one thread object.

Post a Comment

Post a Comment

Have you done this? Click here to let us know.

I Did This

Related Ads

Copyright © 1999-2009 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy.

eHow Computers
eHow_eHow Technology and Electronics