线程无法终止,高手们进来看看

Missna 2009-05-20 12:15:02
启用了个死循环来监听端口,可是在退出的时候用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 晕的不行 有没有强行终止线程的方法


小弟现在没有多少分了,等以后有了给大哥们补上,先谢了!
...全文
133 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
你使用socket来监听串口数据吗
微创社(MCC) 2009-07-26
  • 打赏
  • 举报
回复
private void GetUDPData()中的捕获改一下:
ThreadAbortException

try
{
....
}
catch (ThreadAbortException)
{
....
}
finally
{
....
}



  • 打赏
  • 举报
回复



在while里面做判断
zhoujianzhou 2009-07-14
  • 打赏
  • 举报
回复
6楼的可以..回帖是一种美德!每天回帖即可获得 10 分可用分!
ppyyhh 2009-06-24
  • 打赏
  • 举报
回复
你终止线程的判断条件有问题:
常用如下代码: myThread为活动的线程
if (myThread != null && myThread.IsAlive == true)
{
myThread.Abort();
}
CGabriel 2009-06-23
  • 打赏
  • 举报
回复
需要动用 Thread.Abort 这种威力强大但结果不可预测的武器么

把 isStopThread 赋为 true, 线程就自动结束啦
wodedipanwode 2009-06-23
  • 打赏
  • 举报
回复
你中奖了
ak1ca 2009-05-29
  • 打赏
  • 举报
回复
先试试
UDP_Server.Blocking = false;
UDP_Server.Shutdown(SocketShutdown.Both);
UDP_Server.Close();
Missna 2009-05-20
  • 打赏
  • 举报
回复
怎么没人来啊 自己顶一下
zhaoweiting0609 2009-05-20
  • 打赏
  • 举报
回复
up

1,979

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 其他语言讨论
社区管理员
  • 其他语言社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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