如何解决线程中socket的ReceiveFrom函数阻塞而导致的无法关闭线程的问题?[

DT_hero_last 2012-03-16 10:11:08
有一个线程,利用socket的ReceiveFrom函数获取数据,这个需要绑定端口,如果我想换一个端口绑定,销毁上一个线程,可是上一个线程有可能一直在socket的ReceiveFrom函数这里阻塞而无法关闭,我该怎么办?
...全文
493 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
gomoku 2012-03-16
  • 打赏
  • 举报
回复
例子就20行,认真研究一遍不就知道怎么弄了:)
DT_hero_last 2012-03-16
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 gomoku 的回复:]
比如说你可以关闭那个socket,来终止ReceiveFrom:

C# code

static void Receive(object state)
{
Socket socket = state as Socket;
EndPoint otherEnd = new IPEndPoint(IPAddress.Any, 0);
byte[] buffer ……
[/Quote]
我的主程序很快都执行完了,这些监听都是子线程,绑定的端口通过窗体上的其他界面进行改变,这时进不去主线程了,其他的子线程又不能对这个线程操作,不知道怎么弄
macooidle 2012-03-16
  • 打赏
  • 举报
回复
试试看异步吧
gomoku 2012-03-16
  • 打赏
  • 举报
回复
比如说你可以关闭那个socket,来终止ReceiveFrom:

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();
}
DT_hero_last 2012-03-16
  • 打赏
  • 举报
回复
知道,表示谢谢
DT_hero_last 2012-03-16
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 macooidle 的回复:]
放个public static的变量,用于在下次receive前判断,
比如
while(true)
{
if (var)
{
break;
}

receive...
}
[/Quote]
一直卡住在这个线程里,不往下执行肿么办?
macooidle 2012-03-16
  • 打赏
  • 举报
回复
放个public static的变量,用于在下次receive前判断,
比如
while(true)
{
if (var)
{
break;
}

receive...
}
DT_hero_last 2012-03-16
  • 打赏
  • 举报
回复
有没有大神来帮帮忙啊

111,097

社区成员

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

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

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