crossthread operations error

后端 未结 3 726
礼貌的吻别
礼貌的吻别 2021-01-25 21:43
      if (listBox1.InvokeRequired)
       {
           listBox = new StringBuilder(this.listBox1.Text);
       }

This is the code in c# which when exec

相关标签:
3条回答
  • 2021-01-25 22:21

    Your code should run when InvokeRequired is false

    delegate void SetListBoxDelegate(); 
    
    void SetListBox()
    {
        if(!InvokeRequired)
        {
            listBox = new StringBuilder(this.listBox1.Text);
        } 
        else 
            Invoke(new SetListBoxDelegate(SetListBox)); 
    } 
    

    Edit: Check out Making Windows Forms thread safe

    0 讨论(0)
  • 2021-01-25 22:26

    InvokeRequired simply checks to see if Invoke is required. You found it's required, yet didn't call Invoke!

    0 讨论(0)
  • 2021-01-25 22:31

    InvokeRequired only tells you that an Invoke is necessary in order to validly access the element. It doesn't make the access legal. You must use the invoke method to push the update to the appropriate thread

    Action update = () => listbox = new StringBuilder(this.listBox1.Text);
    if (listBox1.InvokeRequired) {
      listBox1.Invoke(update);
    } else {
      update();
    }
    
    0 讨论(0)
提交回复
热议问题