我有一个在线聊天代码,系统上有一个已登录用户的列表。在listBox
中添加用户名时出现问题;错误如下:Invalid thread operation: control 'lbClients' accessed from a thread that is not the one in which it was created.
我尝试了Invoke
方法,但是它也不起作用。使用Invoke
方法,服务器将用户添加到列表中,但是当用户断开连接时,登录到服务器的用户列表不会刷新。该怎么办?
public void ServiceClient()
{
Socket client = clientsocket;
bool keepalive = true;
while (keepalive)
{
Byte[] buffer = new Byte[1024];
client.Receive(buffer);
string clientcommand = System.Text.Encoding.ASCII.GetString(buffer);
string[] tokens = clientcommand.Split(new Char[]{'|'});
Console.WriteLine(clientcommand);
if (tokens[0] == "CONN")
{
for(int n=0; n<clients.Count; n++) {
Client cl = (Client)clients[n];
SendToClient(cl, "JOIN|" + tokens[1]);
}
EndPoint ep = client.RemoteEndPoint;
//string add = ep.ToString();
Client c = new Client(tokens[1], ep, clientservice, client);
this.Invoke(new Action(() => clients.Add(c)));
string message = "LIST|" + GetChatterList() +"\r\n";
SendToClient(c, message);
try
{
lbClients.Items.Add(c);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
else if (tokens[0] == "CHAT")
{
for(int n=0; n<clients.Count; n++)
{
Client cl = (Client)clients[n];
SendToClient(cl, clientcommand);
}
}
else if (tokens[0] == "PRIV")
{
string destclient = tokens[3];
for(int n=0; n<clients.Count; n++) {
Client cl = (Client)clients[n];
if(cl.Name.CompareTo(tokens[3]) == 0)
SendToClient(cl, clientcommand);
if(cl.Name.CompareTo(tokens[1]) == 0)
SendToClient(cl, clientcommand);
}
}
else if (tokens[0] == "GONE")
{
int remove = 0;
bool found = false;
int c = clients.Count;
for(int n=0; n<c; n++)
{
Client cl = (Client)clients[n];
SendToClient(cl, clientcommand);
if(cl.Name.CompareTo(tokens[1]) == 0)
{
remove = n;
found = true;
lbClients.Items.Remove(cl);
//lbClients.Items.Remove(cl.Name + " : " + cl.Host.ToString());
}
}
if(found)
this.Invoke(new Action(() => clients.RemoveAt(remove)));
client.Close();
keepalive = false;
}
else
{
int remove = 0;
bool found = false;
int c = clients.Count;
for (int n = 0; n < c; n++)
{
Client cl = (Client)clients[n];
//SendToClient(cl, clientcommand);
if (cl.Name.CompareTo(tokens[1]) == 0)
{
remove = n;
found = true;
lbClients.Items.Remove(cl);
//lbClients.Items.Remove(cl.Name + " : " + cl.Host.ToString());
}
}
if (found)
clients.RemoveAt(remove);
client.Close();
keepalive = false;
}
}
}