C# 使用 InvokeRequired 与 control.InvokeRequired
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/527947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using InvokeRequired vs control.InvokeRequired
提问by
What is the difference between InvokeRequired
and somecontrol.InvokeRequired
?
InvokeRequired
和 和有somecontrol.InvokeRequired
什么区别?
like this,
像这样,
delegate void valueDelegate(string value);
private void SetValue(string value)
{
if (InvokeRequired)
{
BeginInvoke(new valueDelegate(SetValue),value);
}
else
{
someControl.Text = value;
}
}
and
和
delegate void valueDelegate(string value);
private void SetValue(string value)
{
if (someControl.InvokeRequired)
{
someControl.Invoke(new valueDelegate(SetValue),value);
}
else
{
someControl.Text = value;
}
}
采纳答案by Jon Skeet
The first version checks the thread responsible for thiscontrol. The second version checks the thread responsible for someControl
. (And ditto for which control's thread they then delegate the invocation to.)
第一个版本检查负责此控制的线程。第二个版本检查负责someControl
. (并且同上,然后他们将调用委托给哪个控件的线程。)
They could potentially be different - although they really shouldn'tbe if the two controls are in the same top-level window. (All controls in one window should be running on the same thread.)
它们可能会有所不同 - 尽管如果两个控件位于同一个顶级窗口中,它们实际上不应该是不同的。(一个窗口中的所有控件都应该在同一线程上运行。)
回答by Dave Van den Eynde
The difference is the control of which you accessing the property. If you access InvokeRequired from within a method on the form, you're effectively access the form's InvokeRequired property.
不同之处在于您访问该属性的控制权。如果您从表单上的方法中访问 InvokeRequired,您实际上是在访问表单的 InvokeRequired 属性。
If the form and the someControl are created in the same thread, then they will return the same value.
如果表单和 someControl 是在同一个线程中创建的,那么它们将返回相同的值。
回答by ?yvind Skaar
It would seem that you in the first example are within the scope of a control, while in the second you are not. The main form is a control just like any other. If someControl is added to the Control collection of the main control, you may use either.
在第一个示例中,您似乎在控件的范围内,而在第二个示例中则不在。主窗体是一个控件,就像任何其他控件一样。如果将 someControl 添加到主控件的 Control 集合中,则可以使用其中之一。