解决VS2005中,线程间不可互操作的问题,一揽子解决方案:
一、首先,定义一个类:SetControlProperty
using System.Reflection;
using System;
using System.Windows.Forms;
namespace Ways.Utils
{
class SetControlProperty
{
delegate void SetValueDelegate(Object obj, Object val, Object[] index);
public SetControlProperty(Control ctrl, String propName, Object val)
{
PropertyInfo propInfo = ctrl.GetType().GetProperty(propName);
Delegate dgtSetValue = new SetValueDelegate(propInfo.SetValue);
ctrl.Invoke(dgtSetValue, new Object[3] { ctrl, val, null });
}
}
}
二、在要操作Form中调用
本例中,此调用是由一通讯事件引发的:
void testcommand_EndStatusEvent(object sender, EventArgs e)
{
new SetControlProperty(label4, "Text", "END");
new SetControlProperty(button1, "Enabled", true);
myComm.EndProtocol();
}
三、 最简化,但却不安全的方案
Control.CheckForIllegalCrossThreadCalls = false;
试过了,在.net compact framework中,不可用!