[英]C# thread safe text update on dynamically created text boxes
我知道如何在已定义的文本框上进行线程安全更新http://msdn.microsoft.com/en-us/library/ms171728.aspx ....如何在文本框上执行此操作后来在程序中生成? 你的建议非常感谢。
给定一些TextBox
对象,只需调用它:
TextBox foo = new TextBox(...);
// Code to add the new box to the form has been omitted; presumably
// you do this already.
Action update = delegate { foo.Text = "Changed!"; };
if (foo.InvokeRequired) {
foo.Invoke(update);
} else {
update();
}
如果您经常使用此模式,则此扩展方法可能会有所帮助:
public static void AutoInvoke(
this System.ComponentModel.ISynchronizeInvoke self,
Action action)
{
if (self == null) throw new ArgumentNullException("self");
if (action == null) throw new ArgumentNullException("action");
if (self.InvokeRequired) {
self.Invoke(action);
} else {
action();
}
}
然后,您可以将代码减少到:
foo.AutoInvoke(() => foo.Text = "Changed!");
这将是正确的事情,在主GUI线程上执行委托,无论您当前是否正在其上执行。
我们在这里肯定需要更多的信息,但是从我可以收集到的信息来看,你感到遗憾的是线程的主要功能没有任何参数。 您可以创建周围类的文本框成员,并以这种方式访问它们。 如果你走这条路,请务必使用互斥锁或其他锁定设备进行线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.