在 C++ CLI 中将参数传递给线程 [英] Pass parameters to thread in C++ CLI
问题描述
我搜索了每个主题以正确创建带有参数 (wstring) 的新线程,但没有任何效果.我该如何解决我的问题?我为我的 .Net UI 应用程序创建了这个项目,所以之前我使用 std::thread 和 std::mutex,但 VSC++ Forms 中的惊人".NET 不支持它.
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
}
推荐答案
从您的代码片段中指出正确的方向并不容易.你需要一个线程对象.
From your code fragment it is not so easy to point in the right direction. You need a thread object.
using namespace System::Threading;
线程对象:
Thread ^m_Thread;
现在需要的行是:
m_Thread = gcnew Thread(gcnew ParameterizedThreadStart(this,
&FileIndex::Diving));
m_Thread->Start(ittr->drive + L"*");
正如 Hans Passant 在他的评论中所建议的那样.Start 方法不会像我认为的 DriverInfo
那样接受本机 c++ 值.您必须将其转换为真正的 C++/CLI 对象.Hans Passant 再次指出了正确的方向:
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;
};
和魔法"调用:
m_Thread->Start(gcnew mywrapwstring(ittr->drive + L"*") );
和线程方法更好:
void FileIndex::Diving(mywrapwstring ^ data)
{
// do smth.
// any recursion
data->str; // here is your string
}
这篇关于在 C++ CLI 中将参数传递给线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!