How do I use MethodInvoker in C++?

眉间皱痕 提交于 2019-12-10 18:14:48

问题


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?


回答1:


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..
    }


来源:https://stackoverflow.com/questions/3247429/how-do-i-use-methodinvoker-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!