调用控件挂起应用程序

时间:2015-06-10 09:10:14

标签: c# multithreading

关注此问题:Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

我已经创建了一个帮助类来包装过程:

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

我称之为:

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

但是,该应用程序挂起在以下行:

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

没有抛出任何错误,等待也没有做任何事情。我在这里看不到什么?

- 编辑 -
对于上下文,这是连接到TCP服务器的客户端TCP应用程序。我想将从服务器收到的结果消息显示在txtOutput

应用程序正确加载并运行,并且只有在单击按钮时才会调用此调用调用。

当我接近Invoke时,这是我当前的线程:

enter image description here

1 个答案:

答案 0 :(得分:1)

这样的事情会起作用。

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