使用委托从后台任务更新 UI
updating UI from background task using delegate
我正在尝试从后台线程更新标签值。我知道有几个例子,但我仍然无法理解为什么下面的代码会抛出堆栈溢出错误。似乎每次执行 setTitle() 时,它都会通过 if 语句的真实部分。
设置标题功能:
void setTitle(char data[])
{
String^ temp = gcnew String(data);
if(this->lastSeen1->InvokeRequired)
{
setTitleDelegate^ d = gcnew setTitleDelegate(this, &setTitle);
d->Invoke(data);
}else
{
this->lastSeen1->Text = temp;
this->lastSeen1->Visible = true;
}
}
代表:
delegate void setTitleDelegate(char data[]);
谢谢
嗯,因为这个:
d->Invoke(data);
看,你在这里调用 Delegate::Invoke
,这基本上意味着 setTitle
只是立即调用它自己。您需要改为调用 Control::Invoke
,因此您需要在 Control
的实例上调用它,如下所示:
this->lastSeen1->Invoke(d, /* any args here */);
我不知道你为什么要在这里传递 char[]
,最好不要过多地混合本机和托管数据结构,如果你可以只使用 String^
(但是即便如此,C++/CLI 也并非真正适合 UI 开发......)。
我正在尝试从后台线程更新标签值。我知道有几个例子,但我仍然无法理解为什么下面的代码会抛出堆栈溢出错误。似乎每次执行 setTitle() 时,它都会通过 if 语句的真实部分。
设置标题功能:
void setTitle(char data[])
{
String^ temp = gcnew String(data);
if(this->lastSeen1->InvokeRequired)
{
setTitleDelegate^ d = gcnew setTitleDelegate(this, &setTitle);
d->Invoke(data);
}else
{
this->lastSeen1->Text = temp;
this->lastSeen1->Visible = true;
}
}
代表:
delegate void setTitleDelegate(char data[]);
谢谢
嗯,因为这个:
d->Invoke(data);
看,你在这里调用 Delegate::Invoke
,这基本上意味着 setTitle
只是立即调用它自己。您需要改为调用 Control::Invoke
,因此您需要在 Control
的实例上调用它,如下所示:
this->lastSeen1->Invoke(d, /* any args here */);
我不知道你为什么要在这里传递 char[]
,最好不要过多地混合本机和托管数据结构,如果你可以只使用 String^
(但是即便如此,C++/CLI 也并非真正适合 UI 开发......)。