以线程安全的方式更改控件

时间:2011-03-17 03:43:50

标签: c# compact-framework

我正在尝试使用来自C#表单的线程安全调用UI控件。由于某种原因, BackgroundWorkerHelper 不可用,可能是因为C#的版本或因为我正在部署到“Window CE 5.0设备”。

我有这个

    //For ThreadSafe called to edit components
    private delegate void SetControlPropertyThreadSafeDelegate(Control control, string propertyName, object propertyValue);
    public static void SetControlPropertyThreadSafe(Control control, string propertyName, object propertyValue)
    {
        if (control.InvokeRequired)
        {
            control.Invoke(new SetControlPropertyThreadSafeDelegate(SetControlPropertyThreadSafe), new object[] { control, propertyName, propertyValue });
        }
        else
        {
            control.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, control, new object[] { propertyValue });
        }

    }

我正在调用线程

private Thread workerThread = new Thread(new ThreadStart(this.remoteRequestBackgroundTask));

workerThread.Start();

然后在remoteRequestBackgroundTask()函数内部我改变了这样的控件

        //enable the cancel button
        SetControlPropertyThreadSafe(btnCancel, "Enabled", true);

问题是当它运行时,调试在这里停止

control.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, control, new object[] { propertyValue });

我得到“NotSupportedException”

1 个答案:

答案 0 :(得分:2)

例外下查看MSDN Documentation for .InvokeMember。在NotSupportedException旁边,您会看到:

  

.NET Compact Framework目前不支持此方法。

在那个else区块,我相信你可以这样做。这与我的一些非常相似的.NET Compact Framework代码相比缩短了:

PropertyInfo propertyInfo = control.GetType().GetProperty(propertyName);
propertyInfo.SetValue(control, propertyValue, null);
相关问题