网口接收数据进行展示,用timer进行定时显示,由于数据量比较大,显示的时候比较耗时,导致timer的触发好像延时了,所以缓存的数据也不对了
别用定时器,那是不行的。实例化一个线程,并设置为哦、后台
主方法:
{
Thread thread = new Thread(ReceiveMessage);
thread.IsBackground = true;
thread.Start(sokConnection);
}
private void ReceiveMessage(object sokConnection)
{
Socket sokClient = sokConnection as Socket;
while (true)
{
byte[] arrMsgRec = new byte[1024*64];
int length = 0;
try
{
length = sokClient.Receive(arrMsgRec);
if (length==0)
{
continue;
}
}
catch (SocketException)
{
登陆列表.Dispatcher.Invoke(
new Action(
delegate
{
if (登陆列表.Items.Contains(sokClient.RemoteEndPoint.ToString()))
{
dict.Remove(sokClient.RemoteEndPoint.ToString());
dictThread.Remove(sokClient.RemoteEndPoint.ToString());
登陆列表.Items.Remove(sokClient.RemoteEndPoint.ToString());
}
})
);
}
byte[] newByte = new byte[length];
Array.Copy(arrMsgRec, 0, newByte, 0, length);
///newByte就是收到的数据直接在这里写好就可以了
//如果是WPF多线程调用
//this.Dispatcher.Invoke(
// new Action(
// delegate
// {
//这里写要执行的内容
// }
// ));
//如果是Winfrom则是
//this.Invoke(
// new Action(
// delegate
// {
//这里写要执行的内容
// }
// ));
}
}