首页 > 解决方案 > 从另一个线程调用委托的返回结果

问题描述

我有一个带有 TabControl 的 GUI。每个新的 TabPage 都是通过一个新的线程创建的。我想调用this->tabControl->TabCount,但tabControl是由我调用的线程以外的线程拥有的。因此,我需要调用一个委托。但是,我在网上找到的所有示例都显示了std::cout每个委托方法的打印。我需要一个返回值,在这种情况下是一个int.

delegate int MyDel();
int InvokeTabCount()
{
    if (this->InvokeRequired)
    {
        MyDel^ del = gcnew MyDel(this, &MyTabControl::InvokeTabCount);
        auto temp = this->Invoke(del); // can't just "return this->Invoke(del)"
        return temp; // Invoke() returns a System::Object^
    }
    else
    {
        return this->tabControl->TabCount;
    }
}

void CreateNewTab()
{
    // do stuff
    this->tabControl->TabPages->Insert(InvokeTabCount() - 1, myNewTab); // insert a tab
    this->tabControl->SelectTab(InvokeTabCount() - 2); // OutOfBounds and tabPageNew
}

System::Void MethodToAddNewTabPage() //actually a click event but whatever
{
    System::Threading::Thread^ newThread = 
        gcnew System::Threading::Thread(
            gcnew System::Threading::ThreadStart(this, &MyTabControl::CreateNewTab));
    newThread->Start();
}

目前,当我没有返回它时,我的InvokeTabCount()方法正在返回。而且我无法做到这一点,因为我的方法期望返回一个而不是返回的。但是,在调试时我发现包含正确的值。并包含正确的值。-1this->Invoke(del)returnintSystem::Object^Invoke()auto temp2temp->ToString()"2"

我该怎么做return this->Invoke(del)


我需要在我的InvokeTabCount()方法中设置全局变量的值吗?我想我可以找到一种将 fromSystem::String^转换std::string为 use的std::stoi()方法,但这似乎是一个奇怪的解决方法。


当前解决方案:

delegate int MyDel();
int InvokeTabCount()
{
    if (this->InvokeRequired)
    {
        MyDel^ del = gcnew MyDel(this, &MyTabControl::InvokeTabCount);
        auto temp = this->Invoke(del);
        return int::Parse(temp->ToString());
    }
    else
    {
        return this->tabControl->TabCount;
    }
}

标签: multithreadingdelegatesc++-cliinvoke

解决方案


结果是一个整数,装箱并包含在Object^参考中。您应该能够简单地将其转换为int.

如果您想更加安全,请进行空检查并验证是否temp->GetType()返回int::typeid,但这可能有点矫枉过正,因为您正在那里创建委托(仍以键入的形式)。


推荐阅读