【发布时间】:2011-04-28 08:44:34
【问题描述】:
我正在用 c# 编写一个表单应用程序,我需要能够从任何线程更改富文本框的内容,我尝试使用 delegate 和 InvokeRequired,但是我创建的委托仍然给我一个跨线程调用错误,并且 InvokeRequired 使表单崩溃,而没有给出错误。 我需要能够从任何线程执行的函数:
public static void updateSub(int what)
{
subDisplay.subBox.Text = tb[what];
}
我尝试使用的委托:
public delegate void UpdateDelegateVoid(int what);
static public UpdateDelegateVoid uSub = new UpdateDelegateVoid(updateSub);
uSub(0);
我的 InvokeRequired 代码:
public static void updateSub(int what)
{
if (subDisplay.subBox.InvokeRequired)
{
subDisplay.subBox.Invoke(new MethodInvoker(finish));
}
else
{
subDisplay.subBox.Text = tb[what];
}
}
我不太确定为什么上面的代码不起作用。谢谢!
【问题讨论】:
-
抱歉,
finish是什么?MethodInvoker是什么? -
subDisplay.subBox.Invoke(new MethodInvoker(finish))这个位是做什么的,为什么它在静态方法中,当然它应该在subDisplay的实例上。subDisplay是静态属性吗? -
@Martinho:
MethodInvoker一直存在到 .Net 1.1,并且在Action出现之前使用。 -
要更接近发生异常的点,您应该在 Visual Studio 中打开 Debug - Exceptions 并选中所有复选框。在这种情况下,编译器将在抛出异常之前中断。
标签: c# winforms delegates multithreading invokerequired