C# cross-thread call problem

前端 未结 3 1472
情书的邮戳
情书的邮戳 2020-12-16 09:07

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 InvokeRe

相关标签:
3条回答
  • 2020-12-16 09:10

    I mostly use this, and it works perfectly. For the exact same purpose are what you are intending.

    public void UpdateSub(string message)
    {
        subDisplay.subBox.Invoke((Action)delegate {
            subDisplay.subBox.Text = message;
        });
    }
    

    Hope it help's your or someone else with it!

    0 讨论(0)
  • 2020-12-16 09:20

    Try this - where you call the same method if an invoke is required.

    public void UpdateSub(string message)
    {
        if (!subDisplay.subBox.InvokeRequired)
        {
            subDisplay.subBox.Text = message;
        }
        else
        {
            var d = new UpdateFormText(UpdateSub);
            Invoke(d, new object[] { message });
        }
    }
    

    Where UpdateFormText is the delegate

    public delegate void UpdateFormText(string message);
    
    0 讨论(0)
  • 2020-12-16 09:28

    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.

    0 讨论(0)
提交回复
热议问题