在异步 OnMsgRecieved 调用中,如果我将值直接分配给控件,则它不起作用。然后我才知道这是由于线程不安全,我得到了以下代码来解决这个问题。现在它正在工作。但我不确定它实际上做了什么。任何人都可以让我完全理解它吗?代码是: -
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 :";
}
}