How to create a Managed Thread in C++ similar to the example in C#

Asked

Viewed 491 times

4

In C# I use the following code to create Managed Thread:

Thread thread = new Thread(new ThreadStart(minhaFuncao));

In C++ i made:

using namespace System::Threading;
    .
    .
    Thread^ thread = gcnew Thread(gcnew ThreadStart(this,PutToSleep));

and when rebuilding, many errors end up being accused, only with these parts of the code.

How to make a Managed thread in C++ that works like the code line above C#?

  • 3

    I believe that it is worth editing the question, to make clear that it is the creation of Managed Threads in C++, using CLR

  • I agree. It would also be good to include the errors accused by the compiler in the question. :)

1 answer

3


The error is on the line

Thread thread = gcnew Thread(gcnew Threadstart(this,Puttosleep));

To create the Managed thread you must pass the method pointer (the &operator is missing), and the method name must be fully qualified:

Thread^ thread = gcnew Thread(gcnew ThreadStart(&NOME_DA_CLASSE::NOME_DO_METODO));

As shown in the example here in MSDN: Thread Class

  • Thanks Rafa, and pq gcnew?? not only new ?? gcnew is to reference ?

  • You have to use gcnew whenever you create an object that goes to Managed heap (where Garbage Collector can act). If you use only new the object goes to the normal heap of the system, and the Garbage Collector has no way to monitor

  • precisely because it is a thread that the execution will end at some point? so when he finishes the thread he already plays in Managed heap pro Garbage Collector do what it takes ??

  • 1

    Actually not only because it is a thread, but because it is a marked object in the class declaration. This Thread class is declared as such public ref class Thread, indicating to the compiler that it should be created with gcnew, to be controlled by Garbage Collector. If the declaration was public class Thread, then it would be the opposite: you could only give new, and not gcnew, by being a common class.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.