通过c ++中的backgroundworker ReportProgress发送int数组

时间:2013-12-11 21:08:40

标签: c++ backgroundworker

我试图通过使用ReportProgress()方法将backgroundworker线程的int数组发送到我的主线程。

现在,如果我尝试发送整数或字符串,它就可以了。但如果我尝试使用int数组,它似乎不起作用。

如何解决这个问题?

private: System::Void backgroundWorker1_DoWork(System::Object^  sender, System::ComponentModel::DoWorkEventArgs^  e) {
    //...do work..
    int foo[5] = { 16, 2, 77, 40, 12071 };
    backgroundWorker1->ReportProgress(99, foo);
}

2 个答案:

答案 0 :(得分:1)

问题可能是您传递给ReportProgress函数的foo参数是一个整数指针。如果发布ReportProgress函数会很有用。

答案 1 :(得分:1)

  

无法将参数2从'int *'转换为'System :: Object ^

C ++ / CLI允许您使用非托管类型,例如int foo[5]。但它们不能转换为System :: Object,它是ReportProgress()的参数类型。您必须在此处使用托管阵列。修正:

 array<int>^ foo = gcnew array<int> { 16, 2, 77, 40, 12071 };
 backgroundWorker1->ReportProgress(99, foo);

然后,您的ProgressChanged事件处理程序需要将Object强制转换回数组:

 array<int>^ foo = safe_cast<array<int>^>(e->UserState);

值得注意的是,您的原始int foo [5]实际上可以使用强制转换为IntPtr,然后可以将其装入Object中。但是在ReportProgress()的特定情况下,非常很差,变量在ProgressChanged事件开始运行的时候已经很久了。 ReportProgress不会等待事件处理程序完成,它使用Control :: BeginInvoke()而不是Invoke()。使用存储在堆上的托管数组可确保此操作不会出错并且数组保持有效。然后,垃圾收集器确保在不再使用数组时释放该数组。