gpt4 book ai didi

c# - Windows 窗体线程到底发生了什么?

转载 作者:太空宇宙 更新时间:2023-11-03 14:02:48 25 4
gpt4 key购买 nike

在异步 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 :";
}
}

最佳答案

当在与 UI 线程不同的线程上调用 ShowResponseMessage 时,InvokeRequired 将返回 true,那么您正在使用 Control.Invoke 将消息发送到 Windows 消息队列。

在UI线程中运行的UI消息泵将拉取消息并传递给目标控件,目标控件然后看到这是一条请求调用委托(delegate)的消息,委托(delegate)由控件调用,它现在在 UI 线程上运行,因此跨线程问题已得到解决。

诀窍在于委托(delegate)不会在非 UI 调用线程上直接调用。使用 Windows 消息,执行委托(delegate)的指令被传递到 UI 线程,然后 UI 线程执行委托(delegate)以响应消息。 'Control.Invoke' 使用 Windows [SendMessage][1]Control.BeginInvoke 使用 [PostMessage][2] Win32 API 来促进消息传递。

关于c# - Windows 窗体线程到底发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10292108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com