C#跨线程调用问题
我正在用 C# 编写一个表单应用程序,我需要能够从任何线程更改富文本框的内容,我尝试使用 delegate 和 InvokeRequired,但我所做的委托仍然给我一个跨线程调用错误,并且 InvokeRequired 使表单崩溃,但没有给出错误。 我需要能够从任何线程执行的函数:
public static void updateSub(int what)
{
subDisplay.subBox.Text = tb[what];
}
我尝试使用的委托:
public delegate void UpdateDelegateVoid(int what);
static public UpdateDelegateVoid uSub = new UpdateDelegateVoid(updateSub);
uSub(0);
我的 InvokeRequired 代码:
public static void updateSub(int what)
{
if (subDisplay.subBox.InvokeRequired)
{
subDisplay.subBox.Invoke(new MethodInvoker(finish));
}
else
{
subDisplay.subBox.Text = tb[what];
}
}
我不太确定为什么上面的代码不起作用。谢谢!
I'm writing a form app in c# and I need to be able to change the contents of a Rich Text Box from any thread, I tried using a delegate and InvokeRequired, but the delegate I made still gives me a cross-thread call error, and InvokeRequired crashes the form, without giving an error.
Function I need to be able to execute from any thread:
public static void updateSub(int what)
{
subDisplay.subBox.Text = tb[what];
}
The delegate I tried to use:
public delegate void UpdateDelegateVoid(int what);
static public UpdateDelegateVoid uSub = new UpdateDelegateVoid(updateSub);
uSub(0);
My InvokeRequired code:
public static void updateSub(int what)
{
if (subDisplay.subBox.InvokeRequired)
{
subDisplay.subBox.Invoke(new MethodInvoker(finish));
}
else
{
subDisplay.subBox.Text = tb[what];
}
}
I'm not really sure why the code above isn't working. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
严格来说,当您检查
InvokeRequired
并发现其为true
时,您应该将调用编组到同一方法。我不确定它是否能解决您的具体问题(我需要查看更多异常详细信息和代码),但这就是我的意思:如果您遇到“奇怪的行为”,请检查表单是否实际上是在主应用程序线程。在 WinForms 中,这不是强制的(就像在 WPF 中一样),因此创建表单的线程实际上可能不是应用程序的根线程。
Strictly speaking, when you check
InvokeRequired
and find it'strue
, you should marshall the call to the same method. I'm not sure it fixes your specific problem (I'd need to see more exception details and code) but this is what I mean:If you're getting "weird behaviour", then check that the form is actually created on the main application thread. In WinForms this isn't forced (as it is in WPF) so it's just possible that the thread that the form was created on isn't actually the root thread of the app.
我主要用这个,而且效果很好。出于完全相同的目的,这就是您的意图。
希望它对您或其他人有所帮助!
I mostly use this, and it works perfectly. For the exact same purpose are what you are intending.
Hope it help's your or someone else with it!
试试这个 - 如果需要调用,您可以调用相同的方法。
其中 UpdateFormText 是委托
Try this - where you call the same method if an invoke is required.
Where UpdateFormText is the delegate