调用必填疑问
将从非 UI 线程调用以下方法。我是否应该检查 InvokeRequired 以在方法中调用这些项目?
一个。 this._moduleStatusGrid.Invalidate()
b. this.Close()
private void CheckIfAllModulesInitComplete()
{
this._moduleStatusGrid.Invalidate();
if (this._moduleDataList.Count(moduleData => !moduleData.IsInitOver) == 0)
{
this._footprint.DeActivate();
this.Close();
}
}
The following method will be invoked from a non UI thread. Should I check InvokeRequired, for calling these items in the method?
a. this._moduleStatusGrid.Invalidate()
b. this.Close()
private void CheckIfAllModulesInitComplete()
{
this._moduleStatusGrid.Invalidate();
if (this._moduleDataList.Count(moduleData => !moduleData.IsInitOver) == 0)
{
this._footprint.DeActivate();
this.Close();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Control.Invoke 和 Control.BeginInvoke 可以安全地从 UI 线程和非 UI 线程调用,因此,如果您已经知道自己位于非 UI 线程上,则跳过检查并仅调用 Invoke/BeginInvoke 没有什么坏处(IMO) 。
例子:
Control.Invoke and Control.BeginInvoke are safe to call from the UI thread and non-UI threads, so if you already know you are on a non-UI thread there is no harm (IMO) skipping the check and just calling Invoke/BeginInvoke.
Example:
听起来您可能会问以下问题之一
Invalidate
和Close
中,我应该检查InvokeRequired属性?
InvokeRequired
属性将始终返回false
,所以我应该避免检查它吗?对于#1,答案是否定的。
Close
和Invalidate
方法没有责任检查InvokeRequired
属性。在调用它们之前,InvokeRequired
属性为 false,这是其契约的隐含部分。对于#2,是的,如果它总是在后台线程上调用,我会跳过检查并直接转到
Invoke
方法。无论哪种情况,我都会按如下方式重写该方法。
It sounds like you could be asking one of the following
Invalidate
andClose
should I be checking theInvokeRequired
property?InvokeRequired
property will always returnfalse
so should I just avoid checking it?For #1 the answer is no. The methods
Close
andInvalidate
don't have a responsibility to check theInvokeRequired
property. It is an implicit part of their contract that theInvokeRequired
property be false before they are called.For #2, yes if it's always called on a background thread I would skip the check and just go straight to the
Invoke
methods.In either case I would rewrite the method as follows.