本文介绍了C#跨线程调用问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在c#中写一个表单应用程序,我需要能够从任何线程更改Rich Text Box的内容,我尝试使用委托 InvokeRequired strong>,但是我所做的委托仍然给我一个跨线程调用错误,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完));
}
else
{
subDisplay.subBox.Text = tb [what];
}
}

我不太确定为什么上面的代码是不工作谢谢!

解决方案

严格来说,当您检查 InvokeRequired 并找到它 true ,您应该调用调用相同的方法。我不确定它修复了你的具体问题(我需要看到更多的例外细节和代码),但这就是我的意思:

  public static void updateSub(int what)
{
if(subDisplay.subBox.InvokeRequired)
{
subDisplay.subBox.Invoke(new Action< int> updateSub),什么);
}
else
{
subDisplay.subBox.Text = tb [what];
}
}

如果你获得奇怪的行为,那么检查表单实际上是在主应用程序线程上创建的。在WinForms中,这并不是强制的(因为它在WPF中),所以创建表单的线程实际上并不是应用程序的根线程。


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!

解决方案

Strictly speaking, when you check InvokeRequired and find it's true, 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:

public static void updateSub(int what)
{
    if (subDisplay.subBox.InvokeRequired)
    {
        subDisplay.subBox.Invoke(new Action<int>(updateSub), what);
    }
    else
    {
        subDisplay.subBox.Text = tb[what];
    }
}

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.

这篇关于C#跨线程调用问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 20:58
查看更多