我创建了一个System::Windows::Forms
类,定义函数:如何创建和运行新线程?
System::Void expanding(System::Windows::Forms::TreeViewEventArgs^ e)
{
//some code
}
,我想通过键入独立的线程调用:
Thread^ thisThread = gcnew Thread(
gcnew ThreadStart(this,&Form1::expanding(e)));
thisThread->Start();
其中e
由afterCheck
函数从treeView
组件通过。
根据this example from MSDN一切都应该正常工作,而是我得到一个编译错误:
error C3350: 'System::Threading::ThreadStart' : a delegate constructor expects 2 argument(s)
和
error C2102: '&' requires l-value
我试图创建的Form1
一个新的实例正是因为它是在表明: MSDN的例子,但我的结果是一样的。
@Tudor推崇的是什么。但使用System :: Threading我无法修改Form1类中的任何组件。 所以我一直在寻找一些其他的解决方案,我已经找到this
也许我不明白的方式BackgroundWorker的的作品,但它会阻止GUI。
我想要实现的是运行单独的线程(无论需要做什么),这将离开gui管理,因此用户将能够停止使用特定按钮进程,并且这个新线程将能够使用来自父线程的组件。
这里是使用BackgroundWorker的我的示例代码
//Worker initialization
this->backgroundWorker1->WorkerReportsProgress = true;
this->backgroundWorker1->DoWork += gcnew System::ComponentModel::DoWorkEventHandler(this, &Form1::backgroundWorker1_DoWork);
this->backgroundWorker1->ProgressChanged += gcnew System::ComponentModel::ProgressChangedEventHandler(this, &Form1::backgroundWorker1_ProgressChanged);
this->backgroundWorker1->RunWorkerCompleted += gcnew System::ComponentModel::RunWorkerCompletedEventHandler(this, &Form1::backgroundWorker1_RunWorkerCompleted);
异步操作由按钮单击事件处理程序
System::Void fetchClick(System::Object^ sender, System::EventArgs^ e) {
dirsCreator();//List of directories to be fetched
backgroundWorker1 ->RunWorkerAsync();
}
DoWork的功能是最基本的递归取回功能
System::Void fetch(String^ thisFile)
{
try{
DirectoryInfo^ dirs = gcnew DirectoryInfo(thisFile);
array<FileSystemInfo^>^dir = (dirs->GetFileSystemInfos());
if(dir->Length>0)
for(int i =0 ;i<dir->Length;i++)
{
if((dir[i]->Attributes & FileAttributes::Directory) == FileAttributes::Directory)
fetch(dir[i]->FullName);
else
**backgroundWorker1 -> ReportProgress(0, dir[i]->FullName);**//here i send results to be printed on gui RichTextBox
}
}catch(...){}
}
调用
这里是报告功能
System::Void backgroundWorker1_ProgressChanged(System::Object^ sender, System::ComponentModel::ProgressChangedEventArgs^ e) {
this->outputBox->AppendText((e->UserState->ToString())+"\n");
this->progressBar1->Value = (this->rand->Next(1, 99));
}
作为说明,Visual C++就是简单的IDE。 C++/CLI是微软为支持托管集成而添加的C++扩展的名称。 – user7116 2012-07-10 17:56:49