BeginInvoke的性能影响

Ang*_*ker 6 c# begininvoke visual-studio-2008 .net-2.0

我继承了从主线程调用BeginInvoke的代码(不是后台线程,通常是模式).我试图了解它在这种情况下的实际作用.

在BeginInvoke中调用的方法是否符合到窗口的消息?文档说asynchronously,这是我的假设.

框架如何确定何时启动BeginInvoke调用的方法?

编辑:代码如下所示:

System.Action<bool> finalizeUI = delegate(bool open)
{
    try
    {
        // do somewhat time consuming stuff
    }
    finally
    {
        Cursor.Current = Cursors.Default;
    }
};

Cursor.Current = Cursors.WaitCursor;
BeginInvoke(finalizeUI, true);
Run Code Online (Sandbox Code Playgroud)

这发生在Form_Load事件中.

Joh*_*ler 4

编辑

现在我们看到了代码,很明显这只是将一些初始化移出 Form_Load 的一种方法,但仍然在用户与表单交互之前发生。

对 Form_load 的调用BeginInvoke是在 Form_load 内部进行的,并且不会在另一个对象上调用,因此这是对 Form.BeginInvoke 的调用。所以发生的事情是这样的。

  1. Form_Load 将委托传递给 Form.BeginInvoke,这会将消息放入表单的消息队列中,该消息位于所有用户输入消息之前。它将光标设置为等待光标。
  2. Form_Load 返回,并且允许完成表单初始化的其余部分,此时表单很可能变得可见。
  3. 一旦代码落入消息泵,队列中首先看到的是委托,因此它会运行它。
  4. 当委托完成时,它将光标更改回正常光标,并返回
  5. 利润!

原帖如下


I 取决于您调用 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);
}
Run Code Online (Sandbox Code Playgroud)

此模式是从主线程而不是从后台线程调用 BeginInvoke 的原因之一。