Skip to main content
 首页 » 编程设计

c#之其他对象引发的工作事件时的跨线程操作

2024年02月20日12davidwang456

我有一个“userdetails”类,它有一个名为“detailschanged”的事件。每当用户详细信息更改时都会引发。
当我在我的新表单中创建“userdetails”(objUserDetails) 的新对象时,我将订阅事件“detailschanged”以指示用户有关数据更改。

objUserDetails.detailschanged += InformtoUser 

InformtoUser 是一种新形式的方法。在 InformtoUser 方法中,我正在访问表单的控件(比如标签的文本属性)。
访问控件时出现“跨线程操作”错误。
如何避免这种跨线程操作??

请您参考如下方法:

这里的问题是线程安全:

Access to Windows Forms controls is not inherently thread safe. If you have two or more threads manipulating the state of a control, it is possible to force the control into an inconsistent state. Other thread-related bugs are possible, such as race conditions and deadlocks. It is important to make sure that access to your controls is performed in a thread-safe way.

It is unsafe to call a control from a thread other than the one that created the control without using the Invoke method.

您需要使用 Control.Invoke在对 Windows 窗体控件进行任何跨线程调用时。

例如:

delegate void SetTextCallback(string text); 
 
private void SetText(string text) 
{ 
    if (textBox.InvokeRequired) 
    {     
        SetTextCallback d = new SetTextCallback(SetText); 
        this.Invoke(d, new object[] { text }); 
    } 
    else 
    { 
        textBox.Text = text; 
    } 
} 

或:

this.Invoke((MethodInvoker) delegate { 
    this.textBox.Text = "Some text here"; 
}); 

更多信息请引用 How to: Make Thread-Safe Calls to Windows Forms Controls .