在C ++中如何使用MethodInvoker? [英] How do I use MethodInvoker in C++?

查看:322
本文介绍了在C ++中如何使用MethodInvoker?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++ / CLI应用程序,它有一个后台线程。几乎每隔一段时间,我想它张贴的结果到主界面。我读过<一个href="http://stackoverflow.com/questions/1136399/how-to-update-textbox-on-gui-from-another-thread-in-c">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..
    }

这篇关于在C ++中如何使用MethodInvoker?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆