简体   繁体   English

如何在C ++中使用MethodInvoker?

[英]How do I use MethodInvoker in C++?

I've got a C++/CLI application which has a background thread. 我有一个C ++ / CLI应用程序,它有一个后台线程。 Every so often I'd like it to post it's results to the main GUI. 我经常希望将结果发布到主GUI。 I've read elsewhere on SO that MethodInvoker could work for this, but I'm struggling to convert the syntax from C# to C++: 我已经在其他地方读过因为MethodInvoker可以为此工作,但我很难将语法从C#转换为C ++:

    void UpdateProcessorTemperatures(array<float>^ temperatures)
    {
        MethodInvoker^ action = delegate
        {
            const int numOfTemps = temperatures->Length;
            if( numOfTemps > 0 ) { m_txtProcessor2Temperature->Text = temperatures[0]; } else { m_txtProcessor2Temperature->Text = "N/A"; }
            if( numOfTemps > 1 ) { m_txtProcessor2Temperature->Text = temperatures[1]; } else { m_txtProcessor2Temperature->Text = "N/A"; }
            if( numOfTemps > 2 ) { m_txtProcessor2Temperature->Text = temperatures[2]; } else { m_txtProcessor2Temperature->Text = "N/A"; }
            if( numOfTemps > 3 ) { m_txtProcessor2Temperature->Text = temperatures[3]; } else { m_txtProcessor2Temperature->Text = "N/A"; }
        }
        this->BeginInvoke(action);
    }

...gives me: ...给我:

1>c:\projects\MyTemperatureReporter\Form1.h(217) : error C2065: 'delegate' : undeclared identifier
1>c:\projects\MyTemperatureReporter\Form1.h(217) : error C2143: syntax error : missing ';' before '{'

What am I missing here? 我在这里错过了什么?

C++/CLI doesn't support anonymous delegates, that's an exclusive C# feature. C ++ / CLI不支持匿名委托,这是一个独有的C#功能。 You need to write the delegate target method in a separate method of the class. 您需要在类的单独方法中编写委托目标方法。 You'll also need to declare the delegate type, MethodInvoker can't do the job. 您还需要声明委托类型,MethodInvoker无法完成工作。 Make it look like this: 看起来像这样:

    delegate void UpdateTemperaturesDelegate(array<float>^ temperatures);

    void UpdateProcessorTemperatures(array<float>^ temperatures)
    {
        UpdateTemperaturesDelegate^ action = gcnew UpdateTemperaturesDelegate(this, &Form1::Worker);
        this->BeginInvoke(action, temperatures);
    }

    void Worker(array<float>^ temperatures) 
    {
        const int numOfTemps = temperatures->Length;
        // etc..
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM