gpt4 book ai didi

c# - 多线程运行时在哪里调用Control.Invoke/BeginInvoke?

转载 作者:行者123 更新时间:2023-11-30 15:24:58 27 4
gpt4 key购买 nike

我在编写一个使用委托(delegate)并从其他线程更新UI的示例时遇到了这个问题。
这是我的示例代码;

public partial class Form1 : Form
{
private decimal _sum;
private delegate void SetSum();
private readonly SetSum _setSum;
public Form1()
{
InitializeComponent();
_setSum = () =>
{
txtSum.Text = _sum.ToString(CultureInfo.InvariantCulture);
};
}
private void btnLoad_Click(object sender, EventArgs e)
{
new Thread(Method).Start();
}
private void Method()
{
for (decimal i = 0; i < 100000000; i++)
{
_sum += i;
}
//txtSum.BeginInvoke(_setSum);
this.BeginInvoke(_setSum);
}
}

如果我在 thistxtSum 上调用 BeginInvoke 方法有什么区别?两者都是来自 UI 线程的控件,并且都没有异常(exception)地调用我的委托(delegate)并且它们的工作非常好,那么如何决定选择哪个控件来调用委托(delegate)?

最佳答案

Control.BeginInvoke() 方法在创建控件的基础句柄的线程上执行...在您的情况下应该没有区别。

根据 MSDN:

The delegate is called asynchronously, and this method returns immediately. You can call this method from any thread, even the thread that owns the control's handle. If the control's handle does not exist yet, this method 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, BeginInvoke will throw an exception.

Most methods on a control can only be called from the thread where the control was created. In addition to the InvokeRequired property, there are four methods on a control that are thread safe: Invoke, BeginInvoke, EndInvoke, and CreateGraphics if the handle for the control has already been created

来自 MSDN 的更多信息:https://msdn.microsoft.com/en-us/library/0b1bf3y3%28v=vs.110%29.aspx

想想这个场景:

public partial class Form1 : Form
{
Control c;

public Form1()
{
Task.Factory.StartNew(() => { c = new Control(); });
}
}

如果您使用 this.BeginInvoke(someMethod),当您尝试从与创建它的线程不同的线程(从 UI 线程)调用 Control 的方法时,它可能会抛出异常在我们的例子中)。所以这时候可能更好地使用 c.BeginInvoke(someMethod)...

关于c# - 多线程运行时在哪里调用Control.Invoke/BeginInvoke?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31959272/

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