在C ++ / CLI中将回调函数传递给线程

问题描述 投票:0回答:1

一些上下文:我知道基本的C ++。我第一次尝试使用C ++ / CLI在Visual Studio中创建GUI应用程序。但是,我在网上找不到关于后者的答案。

我有两个类:MyForm,对应于Windows窗体的主类,和OtherClassMyForm有一个OtherClass类型的对象作为成员。 MyForm的一个函数,在这个例子中是myButton_Click,初始化这个对象并在一个线程中调用它的一个函数:

using namespace System::Threading;

ref class MyForm;
ref class OtherClass;

public ref class MyForm : public System::Windows::Forms::Form {
    public:

    //...

    private:
        OtherClass^ o;

        System::Void myButton_Click(System::Object^  sender, System::EventArgs^  e) {

             //When the button is clicked, start a thread with o->foo
             o = gcnew OtherClass;
             Thread^ testThread = gcnew Thread(gcnew ThreadStart(o, &OtherClass::foo));
             newThread->Start();

        }



};

ref class OtherClass {
    public:
        void foo() {
            //Do some work;
        }
};

到目前为止,这似乎有效。我想要的是将MyClass中的某种回调函数传递给o->foo,以便在foo运行时使用BackgroundWorker的值更新UI。

最好的方法是什么?由于CLI,简单地传递函数指针不起作用。

c++ multithreading callback c++-cli
1个回答
0
投票

我有它的工作。然而,正如@Hans Passant指出的那样,这几乎模仿了BackgroundWorker的行为。无论如何,下面是最热门问题的答案,没有使用a delegate is what's needed。但感觉不是很干净。


正如@ orhtej2指出的那样,stdafx.h。对于上述两个头文件来识别它,我必须在here中声明委托(如建议的delegate void aFancyDelegate(System::String^); ),例如:

MyForm

然后我将这样的委托传递给了OtherClass的构造函数,因此o = gcnew OtherClass; 中的对象初始化行从

aFancyDelegate^ del = gcnew aFancyDelegate(this, &MyForm::callbackFunction);
o = gcnew OtherClass(del);

callbackFunction

.

最后,为了能够从this answer更新UI元素,即使它是从另一个线程调用的,它也必须包含类似这样的东西,如void callbackFunction(String^ msg) { //Make sure were editing from the right thread if (this->txtBox_Log->InvokeRequired) { aFancyDelegate^ d = gcnew aFancyDelegate(this, &MyForm::callbackFunction); this->Invoke(d, gcnew array<Object^> { msg }); return; } //Update the UI and stuff here. //... } 中所建议的:

qazxswpoi
© www.soinside.com 2019 - 2024. All rights reserved.