【问题标题】:Cannot update UI with Invoke() and BeginInvoke() in C#无法在 C# 中使用 Invoke() 和 BeginInvoke() 更新 UI
【发布时间】:2016-07-19 11:15:16
【问题描述】:

我的主要流程:

public void quoteStartReceive()
{
    Thread thdWrite = new Thread(new ThreadStart(DoParseGUIDisplay));
    thdWrite.IsBackground = true;
    thdWrite.Start();
}

我的线程函数:

void DoParseGUIDisplay()
{
    for (int i = 0; i < 1024; i++)
    {
        if (myQueue.Count > 0)
        {
            string strOut = myQueue.Dequeue().ToString();
            Tick tick = new Tick(strOut);
            if (tick.m_last != "")
            {
                string msg = "Update Text";

                if (this.textBox1.InvokeRequired)
                {
                    this.textBox1.BeginInvoke((MethosInvoker)delegate () {this.textBox1.Text = msg; };
                }
                else
                {
                    this.textBox1.Text = msg;
                }
            }
        }
    }
}

无论我尝试使用 Invoke() 还是 BeginInvoke(),我都无法更新 textBox1 中的文本。 我还尝试了另一种方式:

public delegate void UpdateTextCallback(string text);

它仍然无法帮助我更新我的 textBox1。

帮助我找出我错过了什么。谢谢。

【问题讨论】:

  • 我发现每次更新m_last时,属性textBox1.InvokeRequired都是true。完成此过程后,“this.textBox1.BeginInvoke((MethosInvoker)delegate () {this.textBox1.Text = msg; };”,InvokeRequired属性仍然为真。因此,它无法进入“else”条件进行更新我的文本框1。

标签: invoke begininvoke


【解决方案1】:

在线程前添加一个参数:

Application.DoEvents();

并且应该在 m_last 更新之后放置。

【讨论】:

  • 我试过这个方法,效果很好!!我的 textBox1 已成功更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-31
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多