0

后台工作者,传递变量不起作用,在我的示例中,我解释了所有内容,我只放置了重要的函数,我有来自 BackgroundWorker 的其他函数。

int TheFunction(unordered_map<std::string,std::string> options, BackgroundWorker^ worker, DoWorkEventArgs ^ e){

    if(options["option1"].compare("options") == 0){
            //...
        }

        return 0;
}

    void backgroundWorker2_DoWork(Object^ sender, DoWorkEventArgs^ e ){
         BackgroundWorker^ worker = dynamic_cast<BackgroundWorker^>(sender);     
        //e->Result = TheFunction( safe_cast<Int32>(e->Argument), worker, e ); //That's how I do to send an integer value and works just fine, but I don't know how to send non-numeric values with safe_cast or something that works, in the function it looks like this: TheFunction(int index, ...) it works fine, I want to know with unordered_map or with strings also would work, I want more than one argument if you can do with std::string
          e->Result = TheFunction(safe_cast<unordered_map<std::string,std::string>>(e->Argument)); //I tried this, and it didn't work

    }


void CallBackgroundWorker(){
         this->backgroundWorker2 = gcnew System::ComponentModel::BackgroundWorker;
         this->backgroundWorker2->WorkerReportsProgress = true;
         this->backgroundWorker2->WorkerSupportsCancellation = true;
         this->backgroundWorker2->DoWork += gcnew DoWorkEventHandler( this, &GUISystem::backgroundWorker2_DoWork );
         this->backgroundWorker2->RunWorkerCompleted += gcnew RunWorkerCompletedEventHandler( this, &GUISystem::backgroundWorker2_RunWorkerCompleted );
         this->backgroundWorker2->ProgressChanged += gcnew ProgressChangedEventHandler( this, &GUISystem::backgroundWorker2_ProgressChanged );


         unordered_map<std::string,std::string>* options = unordered_map<std::string,std::string>();
         options["option1"] = "valor1";
         options["option2"] = "valor2";

         this->backgroundWorker2->RunWorkerAsync(options);
}

那么我该如何发送 unordered_map 或 std::string (超过 1 个参数)?

提前致谢。这会有很大帮助。

4

1 回答 1

0

这一行:

unordered_map<std::string,std::string>* options = unordered_map<std::string,std::string>();

即使在标准 C++ 中也不合法。指针需要存储地址,而不是对象。所以可能你的意思是说new使用动态分配(毕竟,对象需要生存,直到回调在另一个线程上运行)。

此时,您可以将指针包装在 内System::IntPtr,并在回调中强制转换 的结果ToPointer()

于 2012-04-07T13:18:10.210 回答