Control.Invoke用于在子线程中,把执行UI线程的代码。怎么做到的呢?
分析一下源码。redgate反编译,看到 Control.Invoke源码如下:
public Delegate method, params MultithreadSafeCallScope())
{
return this.MarshaledInvoke(this, method, args, true);
}
}
private Control
caller, object[]
args, int
num;
if (!
this.InvalidOperationException(GetString(
"ErrorNoMarshalingThread"));
}
if (((Properties.PropActiveXImpl)) !=
null)
{
UnmanagedCode.bool
flag =
false;
if ((GetWindowThreadProcessId(
new Handle),
out num) == GetCurrentThreadId()) &&
synchronous)
{
flag =
true;
}
ExecutionContext.ThreadMethodEntry
entry =
new Control
control =
this;
lock (
control)
{
if (
this.threadCallbackList =
new Queue
threadCallbackList =
this.threadCallbackMessage ==
0)
{
SafeNativeMethods.Application.threadCallbackList.InvokeMarshaledCallbacks();
}
else
{
PostMessage(
new Handle), IntPtr.IntPtr.IsCompleted)
{
this.AsyncWaitHandle);
}
if (
entry.exception;
}
return entry.<a title="" object="" system.windows.forms.control+threadmethodentry.retval;"="" href="http://127.0.0.1/roeder/dotnet/Default.aspx?Target=code://System.Windows.Forms:4.0.0.0:b77a5c561934e089/System.Windows.Forms.Control.ThreadMethodEntry/retVal:Object" _xhe_href="http://127.0.0.1/roeder/dotnet/Default.aspx?Target=code://System.Windows.Forms:4.0.0.0:b77a5c561934e089/System.Windows.Forms.Control.ThreadMethodEntry/retVal:Object">retVal;
}