gpt4 book ai didi

动态创建的文本框上的 C# 线程安全文本更新

转载 作者:行者123 更新时间:2023-12-03 13:20:56 24 4
gpt4 key购买 nike

我知道如何对已定义的文本框进行线程安全更新 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 线程上执行委托(delegate),无论您当前是否正在其上执行。

关于动态创建的文本框上的 C# 线程安全文本更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12789773/

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