gpt4 book ai didi

.net - 当 Form.Invoke 已经在正确的线程中时呢?

转载 作者:行者123 更新时间:2023-12-04 06:14:11 25 4
gpt4 key购买 nike

我有一个代码块,必须在与窗口相同的线程中执行。所以我想为此 block 调用 Form.Invoke。但是包含代码块的方法可以从不同的线程调用,其中之一是窗口线程。

所以我的问题是:尽管可能已经在正确的线程中调用了该方法,但可以只使用 Form.Invoke 吗?或者这是否会产生开销,甚至可能是错误的来源?

最佳答案

是的,可以调用Invoke从拥有句柄的线程。

绝大多数代码示例建议您应该测试 InvokeRequired在决定是否调用Invoke之前.

if (control.InvokeRequired) 
{
control.Invoke(action);
}
else
{
action();
}

但是,这会导致代码相当困惑,如果您必须支持来自非 GUI 线程的调用,那么我建议您直接调用 Invoke。在所有情况下直接。与调用 InvokeRequired 相比,开销很小然后直接代表代表团 - 请参阅 Hans Passant 对该问题的评论。但是,只要代理正在执行重要工作,或者此代码不在热点中,开销就应该比代码清晰度更重要。

更多 InvokeRequired在控件的句柄尚未分配时可能会产生误导性结果。 documentation状态:

If the control's handle does not yet exist, InvokeRequired searches up the control's parent chain until it finds a control or form that does have a window handle. If no appropriate handle can be found, the InvokeRequired method returns false.

This means that InvokeRequired can return false if Invoke is not required (the call occurs on the same thread), or if the control was created on a different thread but the control's handle has not yet been created.

In the case where the control's handle has not yet been created, you should not simply call properties, methods, or events on the control. This might cause the control's handle to be created on the background thread, isolating the control on a thread without a message pump and making the application unstable.

You can protect against this case by also checking the value of IsHandleCreated when InvokeRequired returns false on a background thread. If the control handle has not yet been created, you must wait until it has been created before calling Invoke or BeginInvoke. Typically, this happens only if a background thread is created in the constructor of the primary form for the application (as in Application.Run(new MainForm()), before the form has been shown or Application.Run has been called.



所以我会从上面最后引用的段落中得到建议,并替换有风险的 InvokeRequired上面的代码:
control.Invoke(action);

关于.net - 当 Form.Invoke 已经在正确的线程中时呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7470523/

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