ammcom ammcom - 6 months ago 57
C# Question

Exception when writing to socket: Unable to write data to transport connection

I am developing a client server application using sockets in C#, It is a multi Threading application for sure, the strange thing is the following:

The connection is closed from one thread when the remote client asks, in this exact moment the write operation throws this exception:

unable to write data to transport connection: a blocking operation was interrupted by a call to WSACancelblockingcall

Actually I am writing 64 byte each 20 minutes, but the strange thing is that the above exception is thrown each time the connection is closed, that means the write operation is taking very very long time to complete to the extend that the operation is always stopped by the connection close, is this a problem in the network stack?, The more strange thing is that this problem happens only with one client, and still happening for more than a week,so it is not temporary.

Any suggestions? is this a hardware problem? is this a TCP protocol problem? any one had a similar problem and had found a solution?


pseudo code to illustrate the issue:

First thread:

if (some condition)
close connection;

second thread:

sleep for 20 minutes
write(array of 64 bytes) //blocks for a very long period of time


Actually I have found the problem:

The write method of NetwrokStream blocks until it can successfully write data to the underlying socket buffer (although many people disagree with this but the experiment proves that it is correct). When the buffer gets full the write method blocks until some data is sent and there is a room for the data to be written to the buffer, but when the network connection is slow and has issues or when the reader reads data slowly the buffer gets full and write method blocks for a long period of time.