在一个异步的OnMsgRecieved调用中,如果我直接给一个控件赋值,它就不起作用。 然后我才知道这是由于线程不安全,我得到以下代码来解决问题。 现在它工作。但我不确定它在实际中的作用。任何人都可以让我完全理解它吗? 的代码是: -windows窗体线程究竟发生了什么?
public void listener_OnMsgRecieved(string aResponse)
{
ShowResponseMessage(aResponse);
}
public void ShowResponseMessage(string aResponse)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.listBox.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(ShowResponseMessage);
this.Invoke(d, new object[] { aResponse });
}
else
{
this.listBox.Items.Add(aResponse);
label.Text = "Response received from Server :";
}
}
是否存在与同步上下文相关的内容? – userGS 2012-04-24 05:46:06
谢谢,实际解释! – 2012-04-24 06:15:30