multithreading - 从另一个线程调用委托的返回结果
问题描述
我有一个带有 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()
方法正在返回。而且我无法做到这一点,因为我的方法期望返回一个而不是返回的。但是,在调试时我发现包含正确的值。并包含正确的值。-1
this->Invoke(del)
return
int
System::Object^
Invoke()
auto temp
2
temp->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;
}
}
解决方案
结果是一个整数,装箱并包含在Object^
参考中。您应该能够简单地将其转换为int
.
如果您想更加安全,请进行空检查并验证是否temp->GetType()
返回int::typeid
,但这可能有点矫枉过正,因为您正在那里创建委托(仍以键入的形式)。
推荐阅读
- php - Prestashop 1.7 如果产品类别之一,而不是 category_default
- android - 新版本的应用程序出现 Phonegap 格式错误的 config.xml 文件和 Google Play 控制台错误
- python - ImportError:无法从“Crypto.PublicKey”导入名称“RSA”
- java - 仅使用 @mappedBy ,不使用@JoinColumn - 在 OneToMany 关系中创建的连接列,那么 JoinColumn 的用途是什么?
- python-3.x - 在 Windows 中导入 tensorflow 模块时遇到问题
- python - 根据条件将 df 中的列除以另一个 df 值
- python - 在python中解析html的问题
- iframe - 即使父 url 是用 https 加载的,iframe 也会将相对 url 加载为 http
- node.js - 如何实现射击和碰撞
- amazon-s3 - 尝试使用以下配置创建 S3 存储桶时,继续遇到此错误:模板验证错误