Search code examples
multithreadingc++-cliclr

Threading in C++/CLI, CLR


Faced a problem. Need to call a class member method on a separate thread C++/CLI

.h:

ref class BgWorker
{
private:
    void MainLoop();
public:
    void Start();
};

.cpp:

void BgWorker::MainLoop()
{
    while(true)
    {
        ...    
    }
}

void BgWorker::Start()
{
    System::Threading::Thread^ td = gcnew System::Threading::Thread(MainLoop); // v1; didn't working
    System::Threading::Thread^ td = gcnew System::Threading::Thread(gcnew System::Threading::ThreadStart(MainLoop)); // v2; didn't
    System::Threading::Thread^ td = gcnew System::Threading::Thread(gcnew System::Threading::ThreadStart(this, &MainLoop)); // v3; didn't

    std::thread td(MainLoop); // v4, didn't
}

Also tried via System::ComponentModel::DoWorkEventHandler(), most likely i did something wrong

I want to use this constructor, but I can't pull out a link to MainLoop:

public : Thread(System::Threading::ThreadStart^ start)

Same problem with standard stream std::thread, MainLoop is not a function reference

I couldn't find anything on my question on google. Many thanks for the help!


Solution

  • If anyone is interested, here's what I did:

    BgWorker.h:

    ref class BgWorker
    {
        public:
            void MainLoop();
    }
    

    BgWorker.cpp:

    #include "pch.h"
    #include "BgWorker.h"
    
    void BgWorker::MainLoop()
    {
        ...
    }
    

    myProgramm.cpp:

    #include "pch.h"
    #include "BgWorker.h"
    
    int main(array<System::String ^> ^args)
    {
        BgWorker^bg = gcnew BgWorker();
        System::Threading::Thread^ ml = gcnew System::Threading::Thread(gcnew System::Threading::ThreadStart(bg, &BgWorker::MainLoop));
        ml->Name = "MainLoop";
        ml->Start();
    }
    

    It's not exactly what I wanted (didn't want to manage threads in main), but for starters, it's a great result. I also had to get rid of the now unnecessary BgWorker::Start() function.

    Аnd yet, if someone knows how to start a new thread managed by an internal ref class method, I would be very happy with an example.

    EDITED

    Many thanks to Ben Voigt; it this question just looks ridiculously easy now

    With the first structure:

    void BgWorker::Start()
    {
        System::Threading::Thread^ ml = gcnew System::Threading::Thread(gcnew System::Threading::ThreadStart(this, &BgWorker::MainLoop));
        ml->Name = "MainLoop";
        ml->Start();
    }
    

    This question can be closed now.