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();

where由组件的函数e传递。afterChecktreeView

根据这个来自 MSDN 的例子,一切都应该可以正常工作,但是我得到一个编译器错误:

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

错误 C2102:“&”需要左值

我试图创建一个Form1与 MSDN 示例中显示的完全相同的新实例,但我的结果是相同的。


@Tudor adivced 做到了。但是使用System::Threading我无法修改 Form1 类中的任何组件。所以我一直在寻找其他解决方案,我发现了这个

也许我不理解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));
         }
4

1 回答 1

3

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

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

此外,该函数不应带任何参数,否则它不符合ThreadStart签名。

查看更多示例的MSDN 页面。Thread

于 2012-07-10T17:52:33.910 回答