启用了个死循环来监听端口,可是在退出的时候用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 晕的不行 有没有强行终止线程的方法
小弟现在没有多少分了,等以后有了给大哥们补上,先谢了!
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 晕的不行 有没有强行终止线程的方法
小弟现在没有多少分了,等以后有了给大哥们补上,先谢了!
{
//thUdp.Interrupt();
thUdp.Abort();
thUdp.Join();
//thUdp = null;
}
//thUdp.ThreadState = System.Threading.ThreadState.Stopped;
UDP_Server.Close(); 把while改成if试试看吧...
我的做法是ThreadState为Running的时候就调用Abort,调用完就做别的,不要管太多条件判断,千万不要循环调用.那样人可以多活几秒种^_^
这样的话下面的UDP_Server.Close(); 就会抛出线程正在终止的异常了 加了这个while是我在调试的时候想看一下状态到底是什么样的 呵呵 误导大家了!