Cross thread work

Can anyone tell me how other statements are related in this function. I am displaying text from another thread to a GUI thread. What is the order or method of execution. Is an else statement required?

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;
        }
    }

      

+3


source to share


4 answers


  • Another thread calls SetText
  • Since this is not the thread that created the form, it needs it Invoke

    .
  • this.Invoke

    calls SetText again with the given parameter. Also check this
  • Now SetText is called from the UI thread and there is no need to call
  • in the block else

    we are sure that the text is set safely


+4


source


InvokeRequired

used to check the execution of statements on the main UI thread, or on a thread other than the UI thread.



If statements are executed on a thread other than the UI thread, this is Invoke

used to avoid throwing an exception CrossThread

.

+2


source


Required else

.

What this code does is you can safely call SetText

from any thread. If you call it from a thread other than the UI thread ( if

block), it transparently forwards the call to the UI thread ( else

block), which is the only one that can access the control to read or set its text.

Blindly for this.textBox7.Text

will throw an exception if not done on the UI thread.

+2


source


To add to the other answers, this is a common pattern (especially in scenarios where the called method contains a fair amount of logic) - calling back to the same method from the UI thread if it InvokeRequired

returns true:

private void SetText(string text)
{
    if (InvokeRequired)
        BeginInvoke(new Action<string>((t) => SetText(text)));
    else
        textBox7.Text = text;
}

      

This way, you don't have to repeat your logic in if

both else

.

+1


source







All Articles