In my WPF
4.0 application, I have a UDP
listener implemented as shown below. On my Windows 7 PC, I'm running both server and client on localhost
.
Each received datagram is a scanline of a larger bitmap, so after all scanlines have been received the bitmap is shown on the UI
thread. This seems to work. However, occasionally some 1-50% scanlines are missing. I would expect this on a weak network connection, but not when run locally.
What may cause UDP
package loss with the following piece of code?
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, PORT);
udpClient = new UdpClient(endPoint);
udpClient.Client.ReceiveBufferSize = 65535; // I've tried many different sizes...
var status = new UdpStatus()
{
u = udpClient,
e = endPoint
};
udpClient.BeginReceive(new AsyncCallback(UdpCallback), status);
private void UdpCallback(IAsyncResult ar)
{
IPEndPoint endPoint = ((UdpStatus)(ar.AsyncState)).e;
UdpClient client = ((UdpStatus)(ar.AsyncState)).u;
byte[] datagram = client.EndReceive(ar, ref endPoint);
// Immediately begin listening for next packet so as to not miss any.
client.BeginReceive(new AsyncCallback(UdpCallback), ar.AsyncState);
lock (bufferLock)
{
// Fast processing of datagram.
// This merely involves copying the datagram (scanline) into a larger buffer.
//
// WHEN READY:
// Here I can see that scanlines are missing in my larger buffer.
}
}
If I put a System.Diagnostics.Debug.WriteLine
in my callback, the package loss increases dramatically. It seems that a small millisecond delay inside this callback causes problems. Still, the same problem is seen in my release build.
UPDATE
The error becomes more frequent when I stress the UI a bit. Is the UdpClient
instance executed on the main thread?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…