Using Managed C++ to create threads is not as easy as C#. If you already
tried to compile a Managed C++ program with threads, you know what I am talking
First, do not try to add the thread in the same class, it won't
compile. The easiest way I personally found is to create a new managed
class ( remember to add <code lang=mc++>__gc in the beginning of the class declaration ).
In these instance we'll call it <code lang=mc++>CMyThreads. Why not? Every program should
have a CMySomething as a class.
<pre lang=mc++>#pragma once
__gc class CMyThreads
void AddArguments(void* pArg1, void* pArg2)
void * m_FirstArgument ;
void * m_SecondArgument ;
One problem in managed C++ threads is the arguments. You
must create a function to call before starting the thread if you want
arguments. (See <code lang=mc++>AddArguments above)
Calling the thread from another class:
CMyThreads * pMyThread;
pMyThread = new CMyThreads;
ThreadStart * pThread = new ThreadStart(pMyThread, &CMyThreads::MyThreadProc);
Thread *oThread = new Thread(pThread);
Before we create <code lang=mc++>ThreadStart you must call <code lang=mc++>AddArguments if
you want arguments on this thread.
The thread will not begin until you call the member function <code lang=mc++>Start()
<pre lang=mc++>#include "StdAfx.h"
using namespace System;
using namespace System::Threading;
Console::WriteLine(S"Starting Thread... ");
void CMyThreads::AddArguments(void* pArg1, void* pArg2)
m_FirstArgument = pArg1;
m_SecondArgument = pArg2;
Remember to <code lang=mc++>Sleep to allow the main process to continue.
Also you put anything you like in <code lang=mc++>MyThreadProc() you can also call a
function in another class. I hope you have fun!