线程无法终止的问题

Missna 2009-05-20 11:36:46
启用了个死循环来监听端口,可是在退出的时候用abort方法不能终止线程,下面是我的代码:
public void Listen(int port)
{
try
{
isStopThread = false;
UDP_Server_Port = port;
UDP_Server = new UdpClient(port);
thUdp = new Thread(new ThreadStart(GetUDPData));
thUdp.Start();
}
catch(Exception e)
{
throw new Exception(e.Message);
}
}
private void GetUDPData()
{

while (!isStopThread)
{
try
{
byte[] RData = UDP_Server.Receive(ref _Server);
if (DataArrival != null)
{
DataArrival(RData, _Server.Address, _Server.Port);
}
Thread.Sleep(0);

}
catch (Exception e)
{
throw new Exception(e.Message);
if (Sock_Error != null)
{
Sock_Error(e.Message);
}
}
}
}
终止线程代码:
while (thUdp.ThreadState != System.Threading.ThreadState.Stopped)
{
//thUdp.Interrupt();
thUdp.Abort();
thUdp.Join();
//thUdp = null;
}
//thUdp.ThreadState = System.Threading.ThreadState.Stopped;

UDP_Server.Close();

这里thUdp.ThreadState 的状态一直是AbortRequested 晕的不行 有没有强行终止线程的方法


小弟现在没有多少分了,等以后有了给大哥们补上,先谢了!
...全文
100 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Missna 2009-05-24
  • 打赏
  • 举报
回复
唉... 没人理
Missna 2009-05-21
  • 打赏
  • 举报
回复
我开始的时候直接thUdp.Abort()线程,但是abort后线程的状态一直是AbortRequested,而不是stopped
这样的话下面的UDP_Server.Close(); 就会抛出线程正在终止的异常了 加了这个while是我在调试的时候想看一下状态到底是什么样的 呵呵 误导大家了!
starj1 2009-05-21
  • 打赏
  • 举报
回复
while (thUdp.ThreadState != System.Threading.ThreadState.Stopped)
{
//thUdp.Interrupt();
thUdp.Abort();
thUdp.Join();
//thUdp = null;
}
//thUdp.ThreadState = System.Threading.ThreadState.Stopped;

UDP_Server.Close();

把while改成if试试看吧...
我的做法是ThreadState为Running的时候就调用Abort,调用完就做别的,不要管太多条件判断,千万不要循环调用.那样人可以多活几秒种^_^

110,537

社区成员

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

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

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