在C ++中如何使用MethodInvoker?如何使用、MethodInvoker

2023-09-07 09:38:26 作者:Nuisance 讨厌鬼

我有一个C ++ / CLI应用程序,它有一个后台线程。几乎每隔一段时间,我想它张贴的结果到主界面。我读过elsewhere在SO 的MethodInvoker可以工作了这一点,但我挣扎的语法从C#转换为C ++:

I've got a C++/CLI application which has a background thread. Every so often I'd like it to post it's results to the main 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++:

    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不支持匿名委托,这是一个独特的C#的特征。你需要在类的一个单独的方法写的委托目标的方法。您还需要申报的委托类型,MethodInvoker不能做的工作。使它看起来是这样的:

C++/CLI doesn't support anonymous delegates, that's an exclusive C# feature. 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. 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..
    }