请高手来帮小弟我解决UDP侦听占用CPU过高的有关问题


请高手来帮我解决UDP侦听占用CPU过高的问题
请先看我的侦听代码:

udpListener   =   New   Socket(AddressFamily.InterNetwork,   SocketType.Dgram,   ProtocolType.Udp)
_udpListener.Bind(
LocalPoint)
Do   While   _StopListen   =   False
      intRcv   =   _udpListener.ReceiveFrom(byteRcv,   0,   byteRcv.Length,   SocketFlags.None,   thePoint)
      If   intRcv   >   0   Then
            strRcv   &=   Encoding.Default.GetString(byteRcv,   0,   intRcv)
            If   strRcv.EndsWith(SocketEndConst)   Then
                '激发数据接收事件
                ReceiveData(strRcv,   CType(thePoint,   IPEndPoint))
                strRcv   =   " "
            End   If
      End   If
Loop

用新线程启动上面的代码后,CPU占用一直高达48%-50%,无法降低!

请高手帮偶看看问题出在什么地方 有什么解决办法


VBScript .net 程序开发

少年煮温水 13 years, 10 months ago

欧VC的不懂VB语法
但是死等不会造成CPU占用过高,而是线程挂起了
一般CPU占用过高应该是接受的时候瞬间返回了又循环接受,造成忙等
应该稍微“死等”,设置接收超时值或者SLEEP

人称触女收割机 answered 13 years, 10 months ago

ReceiveFrom 你用的是同步 然后不断循环
如果这时候远程没有发送数据包,Receive就会一直在那死等出现阻塞
解决方法 用异步BeginReceive 一切ok 不用循环了

步兵还是骑兵 answered 13 years, 10 months ago

不懂 帮顶

哀愁谁来写 answered 13 years, 10 months ago

使用异步,不能使用循环

雾雨琪露诺 answered 13 years, 10 months ago

都给你说了加个sleep或者用超时或者用同步 不会自己试试啊
Do While _StopListen = False
intRcv = _udpListener.ReceiveFrom(byteRcv, 0, byteRcv.Length, SocketFlags.None, thePoint)
If intRcv > 0 Then //大于0处理了,那小于等于零呢?是不是立马又循环去了~一直循环cpu占用能不高么
strRcv &= Encoding.Default.GetString(byteRcv, 0, intRcv)
If strRcv.EndsWith(SocketEndConst) Then
'激发数据接收事件
ReceiveData(strRcv, CType(thePoint, IPEndPoint))
strRcv = " "
End If
End If
Loop


那么开始零崎吧 answered 13 years, 10 months ago

你要仔细查查到底是不是因为Socket导致CPU跑高。

wakaka answered 13 years, 10 months ago

Dim udpRx As UdpClient = Nothing
Dim udpRxThread As Thread = Nothing


Public Sub UDP_Receive()
Thread.Sleep(1000)
Dim IP As New IPEndPoint(System.Net.IPAddress.Any, 12345)
While True
Dim str As String = System.Text.Encoding.UTF8.GetString(udpRx.Receive(IP))
Dim TW As New IO.StreamWriter( "c:\a.txt ", True)
TW.WriteLine(str)
TW.Flush()
TW.Close()
End While
End Sub

西园寺欣桐 answered 13 years, 10 months ago

恩 不明白 看高人怎么说

bvb123 answered 13 years, 10 months ago

应该是线程竞争资源的问题,作线程同步吧

原来是错觉 answered 13 years, 10 months ago

让侦听线程 sleep 1毫秒试试看。。

水无月清姬 answered 13 years, 10 months ago

借鉴借鉴

带胶布撕鸡 answered 13 years, 10 months ago

用异步模式!

洛伊德·班宁斯 answered 13 years, 10 months ago

Your Answer