请高手来帮小弟我解决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%,无法降低!
请高手帮偶看看问题出在什么地方 有什么解决办法
Answers
都给你说了加个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
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