[英]Update UI item from another class and thread
我在这里看到了其他类似的问题,但似乎无法为我的特定问题找到解决方案。
我正在写一个Twitch Bot,当从服务器收到消息时,需要更新主窗体上的列表框。 我在TwitchBot.cs类中OnReceive
了一个名为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()
方法中TwitchBot
:
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。
您应该检查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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.