Control类中的一段源码,在获取控件句柄的时候有校验:
//
// 摘要:
// Gets the window handle that the control is bound to.
//
// 返回结果:
// An System.IntPtr that contains the window handle (HWND) of the control.
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[DispId(-515)]
[SRDescription("ControlHandleDescr")]
public IntPtr Handle
{
get
{
if (checkForIllegalCrossThreadCalls && !inCrossThreadSafeCall && InvokeRequired)
{
throw new InvalidOperationException(SR.GetString("IllegalCrossThreadCall", Name));
}
if (!IsHandleCreated)
{
CreateHandle();
}
return HandleInternal;
}
}
注意:有些控件,如TextBox,如果赋的新值和原先的旧值相等,也是允许跨线程操作的,因为这些控件在执行set操作时,会先判断新旧值是否相等,如果相等,就不进行任何操作。这点可以看它们的源码。
跨线程情况下,进行get操作是允许的。
备注:
get: 取值
set: 赋值