gpt4 book ai didi

c# - 尝试获取组合框的值时出现 "Cross-thread operation is not valid"异常

转载 作者:行者123 更新时间:2023-11-30 14:32:40 32 4
gpt4 key购买 nike

"Cross-thread operation is not valid" exception

我多次遇到此异常,但所有这些时候我都在设置控件的值。那次我使用名为 SetControlPropertyThreadSafe() 的函数解决了这个问题,该函数仅由 stackoverflow.com 上的某人建议。但是这次我在尝试获取 comboBox 的值时遇到了这个异常。这是代码:

 string cat;
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length > 20)
{
System.Threading.Thread t = new System.Threading.Thread(addQuickTopic);
t.Start();
}
else
MessageBox.Show("The length of the title must be greater than 20", "Title length invalid", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
public string tTitle="";
void addQuickTopic()
{
Global.SetControlPropertyThreadSafe(button1, "Text", "Working...");
Global.SetControlPropertyThreadSafe(button1, "Enabled", false);
Topic t = new Topic();
t.setTitle(textBox1.Text);
t.setDescription(" ");
t.setDesID(Global.getMd5Hash(Common.uid+DateTime.Today.ToString()+DateTime.Today.Millisecond.ToString()));
t.setUsrID(Common.uid);
t.setReplyToID("");
t.setConDate("0");
cat = CategoryList.SelectedValue.ToString();

如您所见,我直接获取了 textBox1.Text,而没有应用任何线程安全操作。但是在最后一行尝试获取组合框的选定值时,我遇到了这个异常。那么有人可以建议我在这种情况下该怎么做吗?以下是用于设置控件值的线程安全函数的代码:

public static void SetControlPropertyThreadSafe(Control control, string propertyName, object propertyValue)
{
try
{
if (control.InvokeRequired)
{
control.Invoke(new SetControlPropertyThreadSafeDelegate(SetControlPropertyThreadSafe), new object[] { control, propertyName, propertyValue });
}
else
{
control.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, control, new object[] { propertyValue });
}
}
catch (Exception)
{ }
}

我是否需要创建一个类似的 get 函数?或任何其他可用的解决方案?

最佳答案

现在,您正在通过 t.setTitle(textBox1.Text);TextBox 获取值。这也会失败。

Should I need to create a similar get function? Or any other solution available?

是的,您需要一个 get 选项。但是,我建议不要使用反射和文本,并对其进行修改以使用通用方法和 lambda。

public static void SetControlPropertyThreadSafe<T>(T control, Action<T> action) where T : Control
{
if (control.InvokeRequired)
{
control.Invoke(action);
}
else
{
action();
}
}

这将允许您编写这种强类型,即:

Global.SetControlPropertyThreadSafe(button1, b => b.Text = "Working...");

你也可以做一个强类型的get方法:

public static U GetControlPropertyThreadSafe<T,U>(T control, Func<T,U> func) where T : Control
{
if (control.InvokeRequired)
{
return (U)control.Invoke(func, new object[] {control});
}
else
{
return func(control);
}
}

然后你可以这样写:

 t.setTitle(Global.GetControlPropertyThreadSafe(textBox1, t => t.Text));

您也可以使用相同的方法获取和设置组合框项目。

关于c# - 尝试获取组合框的值时出现 "Cross-thread operation is not valid"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18086676/

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