gpt4 book ai didi

c# - BeginInvoke 的性能影响

转载 作者:太空狗 更新时间:2023-10-29 21:25:32 24 4
gpt4 key购买 nike

我继承了从主线程调用 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);

这发生在 Form_Load 事件中。

最佳答案

编辑

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

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

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

以下为原帖


I 取决于您对其调用 BeginInvoke 的对象。如果对象派生自 Control,则 Control.BeginInvoke将在创建控件的线程上运行。请参阅 JaredPar 的回答。

但还有另一种使用 BeginInvoke 的模式。如果对象是委托(delegate),则 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 的原因之一。

关于c# - BeginInvoke 的性能影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2473299/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com