ToolStripStatusLabel 没有 InvokeRequired 属性的解决办法
当编写多线程程序时,你希望在线程中修改 Form 窗体上的控件的文本等属性,
但你会得到一个错误:线程间操作无效: 从不是创建控件“xxx”的线程访问它。
引发了“Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException”类型的异常.
这时有一个解决办法就是使用委托来进行 Invoke 调用,
但是你会发现 ToolStripStatusLabel 没有 InvokeRequired 属性!
这个问题存在的原因是什么呢?
我们看看 Textbox 的继承关系:
public abstract class TextBoxBase : Control
再看看 ToolStripStatusLabel 的继承关系:
public abstract class ToolStripItem : Component, IDropTarget, IComponent, IDisposable再看看
ToolStripStatusLabel 的容器 StatusStrip 的继承关系:
public class ScrollableControl : Control, IComponent, IDisposable
我们会发现,这是因为ToolStripItem 是一个组件 Component,而不是一个控件 Control。
解决办法:
方法其实也比较简单,尝试在拥有它们的工具条、状态栏(StatusStrip)上调用扩展方法,并调整委托方法。
实例一:
public class MyForm : System.Windows.Forms.Form {
//UI 元素
private Label lblStatus;
private ProgressBar progressBar1;
//Delegate
pr

在多线程编程中,更新ToolStripStatusLabel时遇到线程间操作异常,因为ToolStripStatusLabel缺少InvokeRequired属性。可以尝试在父控件如StatusStrip上使用Invoke方法,通过扩展方法实现线程安全的更新。示例代码展示了如何正确调用Invoke,避免线程不安全的访问。
最低0.47元/天 解锁文章
4736

被折叠的 条评论
为什么被折叠?



