wpf中服务器端负责侦听的socket放到子线程中区执行侦听,侦听到服务器端连接请求时要跨线程操作UI界面的文本款显示连接成功的状态信息,这时主线程任然会卡死,求解决方案
代码如下:{:soso_e122:}
复制代码
- Socket socketwatch = null;
- private void btn_connection_Click(object sender, RoutedEventArgs e)
- {
- //创建服务端负责监听的Socket
- socketwatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- IPAddress address = IPAddress.Parse(txt_ip.Text);//获取监听的IP地址
- IPEndPoint endpoint = new IPEndPoint(address, int.Parse(txt_port.Text));
- socketwatch.Bind(endpoint);
- socketwatch.Listen(10);// 设置监听队列的长度为10
- Thread listenthread = new Thread(Listen);
- listenthread.IsBackground = true;
- listenthread.Start();
- }
- delegate void ListenDelegate();
- private void Listen()
- {
- if (Dispatcher.Thread != Thread.CurrentThread)
- {
- Dispatcher.Invoke(new ListenDelegate(Listen));
- }
- else
- {
- Socket socketconmunication = socketwatch.Accept();//开始监听
- txt_info.AppendText("与客户端建立链接成功\r\n");
- }
- }
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |