TheGeekZn
TheGeekZn

Reputation: 3914

Invoking control hanging application

Following from this question: Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

I have created a helper class to wrap up the procedure:

public class FormObject
{
    private readonly Form _referenceForm;
    public delegate void SetTextCallback(string text);
    private readonly Control _control;

    public FormObject(Form referenceForm, Control control)
    {
        _referenceForm = referenceForm;
        _control = control;
    }

    public void WriteToControl(string text)
    {
        if (_control.InvokeRequired)
        {
            SetTextCallback d = WriteToControl;
            _referenceForm.Invoke(d, new object[] { text });
        }
        else
        {
            _control.Text = text;
        }
    }
}

Which I call like so:

FormObject fo = new FormObject(this, txtOutput);
fo.WriteToControl("message");

However, the app hangs on the following line:

_referenceForm.Invoke(d, new object[] { text });

There is no error thrown, and waiting doesn't do anything . What am I not seeing here?

-- Edit --
For context, this is a client TCP application connecting to a TCP server. I want to display the resulting message received from the server into the txtOutput.

The application loads and runs correctly, and this invoking call only gets called on a button click.

Here is my current threads when I approach the Invoke:

enter image description here

Upvotes: 0

Views: 101

Answers (1)

Blaatz0r
Blaatz0r

Reputation: 1205

Something like this would work.

    if (_control.InvokeRequired)
    {
       IAsyncResult result = _control.BeginInvoke((Action)(() => control.text = text));
       _control.EndInvoke(result);
    }
    else
    {
        _control.Text = text;
    }

Upvotes: 1

Related Questions