编辑
现在我们看到了代码,很明显这只是一种将一些初始化移出 Form_Load 的方法,但仍然在用户与表单交互之前发生。
调用BeginInvoke
在 Form_load 内部,而不是在另一个对象上调用,因此这是对 Form.BeginInvoke 的调用。所以发生的事情是这样的。
- Form_Load 将委托传递给 Form.BeginInvoke,这会将消息放入表单的消息队列中,该队列位于所有用户输入消息之前。它将光标设置为等待光标。
- Form_Load 返回,并允许表单初始化的其余部分完成,此时表单很可能变得可见。
- 一旦代码进入消息泵,首先在队列中看到的是委托,所以它运行它。
- 当委托完成时,它将光标改回正常光标,并返回
- 利润!
下面是原帖
我取决于您调用 BeginInvoke 的对象。如果对象派生自,Control
则Control.BeginInvoke将在创建控件的线程上运行。请参阅 JaredPar 的回答。
但是还有另一种使用 BeginInvoke 的模式。如果对象是委托,则 BeginInvoke 在单独的线程上运行回调,该线程可能专门为此目的而创建。
public class Foo
{
...
public Object Bar(object arg)
{
// this function will run on a separate thread.
}
}
...
// this delegate is used to Invoke Bar on Foo in separate thread, this must
// take the same arguments and return the same value as the Bar method of Foo
public delegate object FooBarCaller (object arg);
...
// call this on the main thread to invoke Foo.Bar on a background thread
//
public IAsyncResult BeginFooBar(AsyncCallback callback, object arg)
{
Foo foo = new Foo();
FooBarCaller caller = new FooBarCaller (foo.Bar);
return caller.BeginInvoke (arg);
}
这种模式是从主线程而不是后台线程调用 BeginInvoke 的原因之一。