首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

多线程,多人聊天程序有关问题

2012-06-09 
多线程,多人聊天程序问题。学习c#中,望大家指点。程序和问题说明如下。C# codeusing Systemusing System.Col

多线程,多人聊天程序问题。
学习c#中,望大家指点。程序和问题说明如下。

C# code
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Threading;using System.Net.Sockets;namespace WindowsForms{    public partial class Form1 : Form    {        //我想做一个多人聊天的程序,参考了一下网上的代码。        //首先创建一个监听的线程(主线程),然后监听2012端口。一旦有新连接,创建另外一个处理线程        //处理消息,目前发现一些问题(该程序是服务端的)。        //这两个变量在运行时会提示从不是创建的线程访问,如何让这两个变量线程安全访问??        Thread ListenThread;        Thread ServiceThread;        Socket ServiceSocket;        public Form1()        {            InitializeComponent();        }        private void Form1_Load(object sender, EventArgs e)        {            ListenThread = new Thread(new ThreadStart(StartListen));            ListenThread.Start();        }        private void StartListen()        {            TcpListener server = new TcpListener(2012);            server.Start();            while (true)            {                //以下的ServiceSocket和ServiceThread全局变量需要在【标记1】和【标记2】之间不被其他线程更改                //【标记1】                ServiceSocket = server.AcceptSocket();                ServiceThread = new Thread(new ThreadStart(StartService));                ServiceThread.IsBackground = true;                ServiceThread.Start();            }        }        private void StartService()        {            //这里需要得到全局变量ServiceThread和ServiceSocket,仍然会提示从不是创建的线程访问。            //如果不将变量ServiceThread设为全局,如何才能在函数中得到自己是属于哪个线程??            //如果使用委托,这怎么处理啊。需要把【标记1】和【标记2】之间的语句放入委托函数中,不清楚怎么弄。            Thread thread = ServiceThread;            Socket socket = ServiceThread;            //【标记2】            Boolean active = true;            while(active)            {                byte[] buffer = new byte[10000000];                socket.Receive(buffer);                //一些其他处理过程            }        }    }}


[解决办法]
全局变量肯定是不行的,涉及到跨线程的调用问题了,不安全

刚才在论坛里面看到有人讲多线程的问题,里面列举了很多多线程的调用问题,其中封装线程类传递参数那个就比较适合你这里的应用,你自己去研究下吧
http://topic.csdn.net/u/20081002/23/0e911b8e-4cc5-4766-8d26-a885414df3c3.html?80102
[解决办法]
首先如果想互斥可以直接使用lock关键字,其次这代码从整体上就是不合理的。
本身tcpclient自带异步处理方法,无需自己写线程。
调用TcpListener.BeginAcceptSocket即可,自己只需写回调函数。
[解决办法]
http://topic.csdn.net/u/20080619/08/dcef3fe2-f95b-4918-8edb-36d48a3d0528.html

热点排行