线程池类错误,求高人

jiaoshoulee 2008-07-09 11:12:53
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.Windows.Forms;


namespace serverchat
{
public class Receiver
{
Socket _socket = null;
NetworkStream _stream = null;
int _index;
Thread _thread = null;
bool _isFree = true;

#region 属性
public Socket Socket
{
get { return _socket; }
set { _socket = value; }
}

public NetworkStream Stream
{
get { return _stream; }
set { _stream = value; }
}

public int Index
{
get { return _index; }
set { _index = value; }
}

public Thread Thread
{
get { return _thread; }
set { _thread = value; }
}

public bool IsFree
{
get { return _isFree; }
set { _isFree = value; }
}
#endregion

//构造方法
public Receiver()
{
this.Thread = new Thread(new ThreadStart(readData));
this.Thread.Start();

}

//激活此线程
public void active(Socket socket, int index)
{
this.IsFree = false;
this.Socket = socket;
this.Index = index;
this.Stream = new NetworkStream(this.Socket);
this.Thread.Resume();
}

//读取数据
public void readData()
{
lock (this)
{
byte[] by=new byte[1024];
int acture = 0;
string content = null;
while (true)
{
try
{
if (this.IsFree)
{
this.Thread.Suspend();
}
else
{
acture = this.Stream.Read(by, 0, by.Length);
content += Encoding.UTF8.GetString(by, 0, acture);

if (!this.Stream.DataAvailable)
{

Pool.sendText(System.Text.Encoding.UTF8.GetBytes(content));
Pool.appendText(content);
content = null;
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
this.IsFree = true;
this.Stream = null;
this.Socket = null;
throw;

}
}
}
}
}
}


此类当建立的socket断线了,则报错,报错后为什么线程没挂起来呢?
...全文
50 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
greystar 2008-07-10
  • 打赏
  • 举报
回复
MessageBox.Show(e.Message);这个是有问题的.你不能在一个自由线程中处理与界面相关的事务,如修改控件的值.

当双方通信是,有一方退出时,你收到的数据为0,你要自己处理一下,如果为0,则认为对方退出,你要关闭连接.

110,825

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧