我創建了一個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