gpt4 book ai didi

c# - 跨线程属性行为

转载 作者:太空宇宙 更新时间:2023-11-03 11:21:42 24 4
gpt4 key购买 nike

我有一个带有文本框 txtOutput 的窗口窗体。我里面有一些内容。我已经编写了一个属性来获取和设置 txtOutput.Text,既可以在同一线程内也可以跨线程,如下所示:

public string OutputString
{
get
{
string text = string.Empty;
if (txtOutput.InvokeRequired)
{
txtOutput.BeginInvoke(new MethodInvoker(delegate
{
text = txtOutput.Text;
}));
}
else
{
text = txtOutput.Text;
}
return text;
}
set
{
if (txtOutput.InvokeRequired)
{
txtOutput.BeginInvoke(new MethodInvoker(delegate
{
txtOutput.Text = value;
}));
}
else
{
txtOutput.Text = value;
}
}
}

如果我从同一个线程设置/获取属性,则在调用以下函数(如 PrintMessage())时,行为符合预期。

public void PrintMessage()
{
MessageBox.Show(OutputString);
}

但是当我像这样调用 new Thread(PrintMessage).Start() 时。 get 不检索文本框中的值(即,MessageBox 显示空字符串)。当我通过在行上保留断点来执行相同操作时:

txtOutput.BeginInvoke(new MethodInvoker(delegate
{
text = txtOutput.Text;
}));

调试时,检索值(即 MessageBox 显示 txtOutput 内容)

我应该在某个地方 sleep 吗?我在哪里犯了错误?

最佳答案

问题是在 UI 线程可以处理您向调度程序发出的请求之前,您使用对文本变量的引用调用 MessageBox.Show()。我会避免使用 Thread.Sleep(),因为您最终可能会产生一些讨厌的副作用。理想情况下,您应该重构代码以摆脱同步的属性,转而采用更加异步的解决方案。类似于以下代码的内容应该会为您提供所需的结果:

public void PrintMessage(Action<string> displayAction)
{
string text = string.Empty;
if (txtOutput.InvokeRequired)
{
txtOutput.BeginInvoke(new MethodInvoker(delegate
{
displayAction.Invoke(txtOutput.Text);
}));
}
else
{
displayAction.Invoke(txtOutput.Text);
}
}

并调用它:

// Get the text asynchronously
PrintMessage(s => MessageBox.Show(s));

关于c# - 跨线程属性行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10771204/

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