如何创建和运行新线程?

时间:2012-07-10 17:49:56

标签: .net winforms multithreading c++-cli managed-c++

我创建了一个定义函数的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,一切都应该可以正常工作,但我得到编译器错误:

  

错误C3350:'System :: Threading :: ThreadStart':委托构造函数需要2个参数

  

错误C2102:'&'需要l值

我尝试创建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));
         }

1 个答案:

答案 0 :(得分:3)

您不必为函数调用指定参数:

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

该函数也不应该使用任何参数,否则它不符合ThreadStart签名。

请查看Thread的{​​{3}}了解更多示例。