开发者

How do I use MethodInvoker in C++?

开发者 https://www.devze.com 2023-01-07 20:05 出处:网络
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'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_txtProcessor开发者_Python百科2Temperature->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. 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..
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消