How to create threads in Visual C++ .NET or in Visual C++ 2005 (815805)



The information in this article applies to:

  • Microsoft Visual C++ 2005 Express Edition
  • Microsoft Visual C++ .NET (2003)

For a Microsoft Visual Basic .NET version of this article, see 315577.

This article refers to the following Microsoft .NET Framework Class Library namespaces:
  • System::Threading

IN THIS TASK

SUMMARY

You can write multi-threaded applications in Microsoft Visual C++ .NET or in Microsoft Visual C++ 2005. This article describes how a simple Visual C++ .NET or Visual C++ 2005 application can create and manage threads.

back to the top

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft Windows Server 2003, Microsoft Windows 2000, or Microsoft Windows XP
  • Microsoft Visual C++ .NET or Visual C++ 2005
This article assumes that you are familiar with the following topics:
  • Visual C++ programming
  • Visual Studio .NET IDE or Visual Studio 2005 IDE
back to the top

Create a Visual C++ .NET or Visual C++ 2005 application with threads

  1. Start Microsoft Visual Studio .NET 2003 or Microsoft Visual Studio 2005.
  2. On the File menu, point to New, and then click Project.
  3. Click Visual C++ Projects under Project Types, and then click Windows Forms Application (.NET) under Templates. Name the project ThreadWinApp.

    Note In Visual Studio 2005, click Visual C++ under Project Types, and then click Windows Forms Application under Templates.
  4. Add a Button control to Form1. By default, the button is named Button1.
  5. Add a ProgressBar control to Form1. By default, the progress bar is named progressBar1.
  6. Right-click Form1, and then click View Code.
  7. Add the following statement to the beginning of the file.
    using namespace System::Threading;
  8. Double-click button1 on Form1. Modify the button1 event handler as follows.
    private: System::Void button1_Click(System::Object *  sender, System::EventArgs *  e)
    {
        MessageBox::Show(S"This is the main thread");
    }
  9. Add the following variable to the Form1 class.
    private: Thread *trd;
  10. Add the following code at the beginning of the Dispose() method of the Form1 class.
    if (trd->IsAlive)
    	trd->Abort();
  11. Add the following code to the Form1 class.
    __delegate void DelegateThreadTask();
    private: void ThreadTask()
    {
    	int stp;
    	int newval;
    	Random *rnd=new Random();
    
    	if (progressBar1->InvokeRequired == false)
    		{
    		stp=this->progressBar1->Step*rnd->Next(-1,2);
    		newval = this->progressBar1->Value + stp;
    
    		if (newval > this->progressBar1->Maximum)
    			newval = this->progressBar1->Maximum;
    		else if (newval < this->progressBar1->Minimum)
    			newval = this->progressBar1->Minimum;
    
    		this->progressBar1->Value = newval;
    		}
    	else 
    		{
    		DelegateThreadTask *myThreadDelegate = new DelegateThreadTask(this,ThreadTask);
    		this->Invoke(myThreadDelegate);			
    		}
    }
    private: void repeat()
    {	
    	while(true)
    	{
    	ThreadTask();
    	Thread::Sleep(100);
    	}
    }
    Notes You must add the common language runtime support compiler option (/clr:oldSyntax) in Visual C++ 2005 to successfully compile the previous code sample. To add the common language runtime support compiler option in Visual C++ 2005, follow these steps:
    1. Click Project, and then click <ProjectName> Properties.

      Note <ProjectName> is a placeholder for the name of the project.
    2. Expand Configuration Properties, and then click General.
    3. Click to select Common Language Runtime Support, Old Syntax (/clr:oldSyntax) in the Common Language Runtime support project setting in the right pane, click Apply, and then click OK.
    For more information about the common language runtime support compiler option, visit the following Microsoft Web site:

    /clr (Common Language Runtime Compilation)
    http://msdn2.microsoft.com/en-us/library/k8d11d4s.aspx

    This is the code that underlies the thread. This code is an infinite loop that randomly increments or decrements the value in the progressBar1 variable name, and then waits 100 milliseconds before it continues.
  12. Double-click anywhere on Form1. Modify the Load event handler for Form1 as follows. This code creates a new thread, makes the thread a background thread, and then starts the thread.
    private: System::Void Form1_Load(System::Object *  sender, System::EventArgs *  e)
    {
        ThreadStart *myThreadDelegate = new ThreadStart(this, repeat);
        trd = new Thread(myThreadDelegate);
        trd->IsBackground = true;
        trd->Start();
    }
back to the top

Verify that it works

  1. Build, and then run the application. Notice that the value in the progressBar1 variable name changes randomly. This is the new thread in operation.
  2. To demonstrate that the main thread is independent of the thread that changes the progressBar1 value, click the button on the form. You receive a dialog box with the following information message: This is the main thread
  3. Wait for input. Notice that the progressBar1 value continues to change.
back to the top

Troubleshooting

In more complex applications, make sure that you synchronize multiple threads when you access shared variables. For more information, see the lock statement and the related topics in Visual C++ .NET online Help documentation.

back to the top

REFERENCES

For more information about the Thread class, visit the following Microsoft Developer Network (MSDN) Web site or the Microsoft .NET Framework SDK documentation: For more information about the Multithreading safety, visit the following Microsoft Developer Network (MSDN) Web site or the Microsoft .NET Framework SDK documentation: back to the top

Modification Type:MajorLast Reviewed:1/5/2006
Keywords:kbThread kbHOWTOmaster KB815805 kbAudDeveloper kbAudITPRO