code-factory
code-factory

Reputation: 259

Improve Socket performance

I have a TCP/IP socket and communicate to an external sensor device over it. The proprietary protocol that we use has a feature that the device can send a packet to the client at any time. This is called an "event" and is very much like a C# event.

I basically implemented it like this:

...
socket.ReceiveTimeout = ResolveTimeout(timeout);
while (...)
{
    var buffer = new byte[count];
    int readBytes = socket.Receive(buffer, 0, count, SocketFlags.None);
    ...
}

With this code, the application suffers bad performance. I measured it in a profiler and it tells me that Socket.Receive needs 45% wall time.

Is there any way how I can improve this?

Upvotes: 0

Views: 356

Answers (1)

CodeCaster
CodeCaster

Reputation: 151720

That's most likely because Socket.Receive() blocks until data is available.

Try asynchronous programming, using Socket.BeginReceive().

Upvotes: 1

Related Questions