【问题标题】:Update UI item from another class and thread从另一个类和线程更新 UI 项
【发布时间】:2015-07-20 17:31:19
【问题描述】:

我在这里看到了其他类似的问题,但我似乎无法为我的特定问题找到解决方案。

我正在编写一个 Twitch Bot,并且需要在从服务器接收到消息时更新主窗体上的列表框。我在我的 TwitchBot.cs 类中创建了一个名为 OnReceive 的自定义事件,如下所示:

public delegate void Receive(string message);
public event Receive OnReceive;

private void TwitchBot_OnReceive(string message)
{
    string[] messageParts = message.Split(' ');
    if (messageParts[0] == "PING")
    {
        // writer is a StreamWriter object
        writer.WriteLine("PONG {0}", messageParts[1]);
    }
}

事件在我的TwitchBot 类的Listen() 方法中引发:

private void Listen()
{
    //IRCConnection is a TcpClient object
    while (IRCConnection.Connected)
    {
        // reader is a StreamReader object.
        string message = reader.ReadLine();

        if (OnReceive != null)
        {
            OnReceive(message);
        }
    }
}

当连接到 IRC 后端时,我从一个新线程调用Listen() 方法:

Thread thread = new Thread(new ThreadStart(Listen));
thread.Start();

然后我使用以下行在主窗体中订阅了OnReceive 事件:

// bot is an instance of my TwitchBot class
bot.OnReceive += new TwitchBot.Receive(UpdateChat);

最后,UpdateChat() 是主窗体中用于更新列表框的方法:

private void UpdateChat(string message)
{
    lstChat.Items.Insert(lstChat.Items.Count, message);
    lstChat.SelectedIndex = lstChat.Items.Count - 1;
    lstChat.Refresh();
}

当我连接到服务器并运行 Listen() 方法时,我收到一个 InvalidOperationException,上面写着“附加信息:跨线程操作无效:控制 'lstChat' 从线程之外的线程访问创建于。”

我查看了如何从不同的线程更新 UI,但只能找到 WPF 的内容,而且我正在使用 winforms。

【问题讨论】:

标签: c# multithreading winforms irc


【解决方案1】:

你应该检查Invoke for UI thread

private void UpdateChat(string message)
{
    if(this.InvokeRequired)
    {
        this.Invoke(new MethodInvoker(delegate {
            lstChat.Items.Insert(lstChat.Items.Count, message);
            lstChat.SelectedIndex = lstChat.Items.Count - 1;
            lstCat.Refresh();
        }));           
    } else {
            lstChat.Items.Insert(lstChat.Items.Count, message);
            lstChat.SelectedIndex = lstChat.Items.Count - 1;
            lstCat.Refresh();
    }
}

【讨论】:

  • 太棒了!这正是我所需要的。感谢您链接该信息丰富的文章并向我展示如何使用调用。现在效果很好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
  • 2012-11-22
  • 1970-01-01
  • 1970-01-01
  • 2019-06-30
相关资源
最近更新 更多