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事件中.
现在我们看到了代码,很明显这只是将一些初始化移出 Form_Load 的一种方法,但仍然在用户与表单交互之前发生。
对 Form_load 的调用BeginInvoke是在 Form_load 内部进行的,并且不会在另一个对象上调用,因此这是对 Form.BeginInvoke 的调用。所以发生的事情是这样的。
原帖如下
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 的原因之一。
| 归档时间: |
|
| 查看次数: |
2043 次 |
| 最近记录: |