2012-07-10 79 views
0

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

其中eafterCheck函數從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)); 
     } 
+0

作爲說明,Visual C++就是簡單的IDE。 C++/CLI是微軟爲支持託管集成而添加的C++擴展的名稱。 – user7116 2012-07-10 17:56:49

回答

3

您不必指定參數的函數調用:

Thread^ thisThread = gcnew Thread(
     gcnew ThreadStart(this,&Form1::expanding)); 
     thisThread->Start(); 

而且功能不應該採取任何參數,否則不符合ThreadStart簽名。

查看ThreadMSDN page瞭解更多示例。

+1

+1,在OP的示例中,他試圖獲取方法調用返回值的地址。 – user7116 2012-07-10 17:57:55

+1

對於實例方法,「Form1 :: expanding」在C++/CLI中是正確的。委託構造函數「this」的第一個參數指定調用該方法的對象。 – 2012-07-10 18:20:54

+0

@David Yaw:對,對不起,我不知道我在想什麼。 :) – Tudor 2012-07-10 18:24:46