C# 以线程安全的方式更改控件
我正在尝试从C#表单使用threadsafe调用UI控件。由于某些原因,BackgroundWorkerHelper不可用,可能是因为C#的版本,也可能是因为我正在部署到“Window CE 5.0设备” 我有这个C# 以线程安全的方式更改控件,c#,compact-framework,C#,Compact Framework,我正在尝试从C#表单使用threadsafe调用UI控件。由于某些原因,BackgroundWorkerHelper不可用,可能是因为C#的版本,也可能是因为我正在部署到“Window CE 5.0设备” 我有这个 //For ThreadSafe called to edit components private delegate void SetControlPropertyThreadSafeDelegate(Control control, string property
//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();
//enable the cancel button
SetControlPropertyThreadSafe(btnCancel, "Enabled", true);
然后在remoteRequestBackgroundTask()函数中,我更改如下控件
private Thread workerThread = new Thread(new ThreadStart(this.remoteRequestBackgroundTask));
workerThread.Start();
//enable the cancel button
SetControlPropertyThreadSafe(btnCancel, "Enabled", true);
问题是,当它运行时,调试在此停止
control.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, control, new object[] { propertyValue });
我得到了“NotSupportedException”看看异常下的。在NotSupportedException
旁边,您将看到:
.NET Compact Framework当前不支持此方法
在else
块中,我相信您可以这样做。这是从我的一些非常类似的.NET Compact Framework代码中截取的:
PropertyInfo propertyInfo = control.GetType().GetProperty(propertyName);
propertyInfo.SetValue(control, propertyValue, null);