日期:2014-05-18  浏览次数:21063 次

如何解决线程中socket的ReceiveFrom函数阻塞而导致的无法关闭线程的问题?[
有一个线程,利用socket的ReceiveFrom函数获取数据,这个需要绑定端口,如果我想换一个端口绑定,销毁上一个线程,可是上一个线程有可能一直在socket的ReceiveFrom函数这里阻塞而无法关闭,我该怎么办?

------解决方案--------------------
比如说你可以关闭那个socket,来终止ReceiveFrom:
C# code

static void Receive(object state)
{
    Socket socket = state as Socket;
    EndPoint otherEnd = new IPEndPoint(IPAddress.Any, 0);
    byte[] buffer = new byte[6400];
    try
    {
        socket.ReceiveFrom(buffer, ref otherEnd);
    }
    catch (SocketException se)
    {
        Console.WriteLine(se.Message);
    }
}
static void Main()
{
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    socket.Bind(new IPEndPoint(IPAddress.Any, 12345));

    ThreadPool.QueueUserWorkItem(Receive, socket);
    Thread.Sleep(2 * 1000);

    socket.Shutdown(SocketShutdown.Both);
    socket.Close();                        //<---
    Console.WriteLine("socket closed");
    Console.ReadLine();
}

------解决方案--------------------
试试看异步吧
------解决方案--------------------
放个public static的变量,用于在下次receive前判断,
比如
while(true)
{
if (var)
{
break;
}

receive...
}