C# 如何使用Invoke on InvokeRequired处理PropertyGrid更改?

C# 如何使用Invoke on InvokeRequired处理PropertyGrid更改?,c#,.net,thread-safety,propertygrid,C#,.net,Thread Safety,Propertygrid,我正在使用Activator提供的COM对象 当属性在那里更改时,它也会提供事件,但我的PropertyGrid无法及时更新它们,因为它来自另一个线程,我得到: A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll A first chance exception of type 'System.InvalidOperationExcepti

我正在使用Activator提供的COM对象

当属性在那里更改时,它也会提供事件,但我的PropertyGrid无法及时更新它们,因为它来自另一个线程,我得到:

A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
当外部线程导致内部
onChange
更改时,如何自动调用属性更新

可能的修复方法是:
CheckForIllegalCrossThreadCalls=false


但是有可能以正确的方式处理这种情况吗?

假设您正在将对象绑定到PropertyGrid,每当对象的属性发生更改时,它应该在GUI线程中触发PropertyChanged事件,以便PropertyGrid正确更新

将属性设置程序封送到GUI线程是您的职责。如果可以链接到任何控件,请使用该控件调用。否则,一般的解决方案是在开始时创建一个虚拟控件,并将其用于调用

public partial class ControlBase : UserControl
{
    /// <summary>
    /// Dummy control, use for invoking
    /// </summary>
    public static Control sDummyControl = null;

    /// <summary>
    /// Constructor
    /// </summary>
    public ControlBase()
    {
        InitializeComponent();

        if (sDummyControl == null)
        {
            sDummyControl = new Control();
            sDummyControl.Handle.ToString(); // Force create handle
        }
    }
}
在您的对象中:

    public string Name
    {
        get { return _name; }
        set { _name = value; RaisePropertyChanged(this, new PropertyChangedEventArgs("Name")); }
    }
嗯,,
Huy

您需要像下面的回答那样包装您的对象:但是您需要向DynamicPropertyDescriptor添加代码,以便它能够捕获内部/COM对象事件并在UI线程上重新访问它们
    public string Name
    {
        get { return _name; }
        set { _name = value; RaisePropertyChanged(this, new PropertyChangedEventArgs("Name")); }
    }