Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross thread operation

Can anybody tell me how if and else statements are related in this function. I am displaying text from another thread to GUI thread. What's the order or way of execution. Is the else statement necessary?

delegate void SetTextCallback(string text);

    private void SetText(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.textBox7.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.textBox7.Text = text;
        }
    }
like image 782
user1903439 Avatar asked May 01 '26 16:05

user1903439


2 Answers

  1. The other thread calls SetText
  2. Since it is not the thread that created the Form it requires Invoke.
  3. this.Invoke calls SetText with the given parameter again. Also check this
  4. Now SetText is called from the UI thread and there is no need to Invoke
  5. in else block we are sure text is set thread safely
like image 144
Mehmet Ataş Avatar answered May 03 '26 05:05

Mehmet Ataş


InvokeRequired is used to check whether the statements are executed in the main UI thread or in an other thread than UI thread.

If the statements are being executed in an other thread than UI thread, Invoke is used to not to cause any CrossThread exception.

like image 44
daryal Avatar answered May 03 '26 06:05

daryal