Arsen Boykanych
Arsen Boykanych

Reputation: 13

Pass parameters to thread in C++ CLI

I searched every topic to correctly create new thread with parameter (wstring) but nothing works. How can I solve my problem? This project I create to my .Net UI Application, so earlier I use std::thread and std::mutex but "amazing" .NET in VSC++ Forms doesn't doesn't support it.

namespace indx
{
ref class FileIndex
{
public:
    FileIndex();
    FileIndex(FileIndex ^);
    virtual ~FileIndex();

    // func
    void getDrives();
    void Diving(const wstring &);
    void Processing();
};

void FileIndex::Diving(Object^ data)
{
    // do smth.
    // any recursion 
}

void FileIndex::Processing()
{
    vector<DriveInfo>::iterator ittr = LDrivers->begin();
    for(counter = 0; ittr != LDrivers->end(); ittr++)
    {
        if(ittr->type == L"Fixed" || ittr->type == L"Removable")
        {
            // need new thread(&FileIndex::Diving, this, (ittr->drive + L"*"));
            // argument - ittr->drive + L"*";
        }
    }
    // join
}

Upvotes: 0

Views: 4032

Answers (1)

Martin Schlott
Martin Schlott

Reputation: 4547

From your code fragment it is not so easy to point in the right direction. You need a thread object.

using namespace System::Threading;

The thread object:

Thread ^m_Thread;

and the needed line is now:

m_Thread = gcnew Thread(gcnew ParameterizedThreadStart(this,
                    &FileIndex::Diving));
m_Thread->Start(ittr->drive + L"*");

As Hans Passant suggest in his comment. The Start method will not accept a native c++ value like I think DriverInfo is. You have to convert it to a real C++/CLI object. And again Hans Passant point into the right direction:

ref class mywrapwstring
{
 public:
  mywrapwstring(std::wstring str) :  str(new std::wstring(str)) {}
  !mywrapwstring() :  { delete std::string(str); }
  std::wstring *str;
};

and the "magic" call:

m_Thread->Start(gcnew mywrapwstring(ittr->drive + L"*") ); 

and the thread method better like:

void FileIndex::Diving(mywrapwstring ^ data)
{
 // do smth.
 // any recursion 
 data->str; // here is your string
}

Upvotes: 2

Related Questions