51

My application is working as a client application for a bank server. The application is sending a request and getting a response from the bank. This application is normally working fine, but sometimes

The I/O operation has been aborted because of either a thread exit or an application request

error with error code as 995 comes through.

public void OnDataReceived(IAsyncResult asyn)
{
    BLCommonFunctions.WriteLogger(0, "In :- OnDataReceived", 
                                        ref swReceivedLogWriter, strLogPath, 0);
    try
    {
        SocketPacket theSockId = (SocketPacket)asyn.AsyncState;

        int iRx = theSockId.thisSocket.EndReceive(asyn); //Here error is coming
        string strHEX = BLCommonFunctions.ByteArrToHex(theSockId.dataBuffer);                    

    }
}

Once this error starts to come for all transactions after that same error begin to appear, so please help me to sort out this problem. If possible then with some sample code

Regards, Ashish Khandelwal

David Klempfner
  • 8,700
  • 20
  • 73
  • 153
funsukvangdu
  • 1,621
  • 4
  • 20
  • 33
  • There are few Windows errors that are as descriptive and reliable as that one. We can't help you find the thread that is terminating too early. Add some tracing to your code if you can't find it. – Hans Passant Aug 29 '11 at 10:37
  • I had this exception raised while using IPython, when simply running code defining a function, and the code had nothing to do with client-server communication. For those with similar issues, [see this SO question](https://stackoverflow.com/questions/59355904/why-do-i-get-an-unhandled-exception-in-event-loop-error-on-ipython). – Lfppfs Jan 05 '22 at 16:38

8 Answers8

28

995 is an error reported by the IO Completion Port. The error comes since you try to continue read from the socket when it has most likely been closed.

Receiving 0 bytes from EndRecieve means that the socket has been closed, as does most exceptions that EndRecieve will throw.

You need to start dealing with those situations.

Never ever ignore exceptions, they are thrown for a reason.

Update

There is nothing that says that the server does anything wrong. A connection can be lost for a lot of reasons such as idle connection being closed by a switch/router/firewall, shaky network, bad cables etc.

What I'm saying is that you MUST handle disconnections. The proper way of doing so is to dispose the socket and try to connect a new one at certain intervals.

As for the receive callback a more proper way of handling it is something like this (semi pseudo code):

public void OnDataReceived(IAsyncResult asyn)
{
    BLCommonFunctions.WriteLogger(0, "In :- OnDataReceived", ref swReceivedLogWriter, strLogPath, 0);

    try
    {
        SocketPacket client = (SocketPacket)asyn.AsyncState;

        int bytesReceived = client.thisSocket.EndReceive(asyn); //Here error is coming
        if (bytesReceived == 0)
        {
          HandleDisconnect(client);
          return;
        }
    }
    catch (Exception err)
    {
       HandleDisconnect(client);
    }

    try
    {
        string strHEX = BLCommonFunctions.ByteArrToHex(theSockId.dataBuffer);                    

        //do your handling here
    }
    catch (Exception err)
    {
        // Your logic threw an exception. handle it accordinhly
    }

    try
    {
       client.thisSocket.BeginRecieve(.. all parameters ..);
    }
    catch (Exception err)
    {
       HandleDisconnect(client);
    }
}

the reason to why I'm using three catch blocks is simply because the logic for the middle one is different from the other two. Exceptions from BeginReceive/EndReceive usually indicates socket disconnection while exceptions from your logic should not stop the socket receiving.

jgauffin
  • 99,844
  • 45
  • 235
  • 372
  • 1
    Dear jgauffin, Thanks for your response, but issue is that only client application is from our company and server is from some bank, so if socket closed from their side then how to express them that this problem is from their side also how can we handle this without exception i.e. as it throws exception in endreceive can we write any command which will tell us that receiving data is 0 – funsukvangdu Aug 30 '11 at 10:34
  • 1
    @funsukvangdu: Do you have any more questions? – jgauffin Oct 30 '15 at 07:22
  • More info on error 995: https://stackoverflow.com/a/14480048/67824 – Ohad Schneider Aug 21 '20 at 20:11
24

In my case, the request was getting timed out. So all you need to do is to increase the time out while creating the HttpClient.

HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromMinutes(5);
Avshalom
  • 8,657
  • 1
  • 25
  • 43
Abhishek kumar
  • 245
  • 2
  • 3
7

I had the same issue with RS232 communication. The reason, is that your program executes much faster than the comport (or slow serial communication).

To fix it, I had to check if the IAsyncResult.IsCompleted==true. If not completed, then IAsyncResult.AsyncWaitHandle.WaitOne()

Like this :

Stream s = this.GetStream();
IAsyncResult ar = s.BeginWrite(data, 0, data.Length, SendAsync, state);
if (!ar.IsCompleted)
    ar.AsyncWaitHandle.WaitOne();

Most of the time, ar.IsCompleted will be true.

Athafoud
  • 2,898
  • 3
  • 40
  • 58
user4624881
  • 71
  • 1
  • 1
  • If the `EndWrite` is directly below that code, you should use `Write` instead of your code. There is no performance improvement of using Begin/WaitOne/End, on the contrary, the code will be slower and waste allocations. – jgauffin Jan 07 '20 at 17:45
3

I had this problem. I think that it was caused by the socket getting opened and no data arriving within a short time after the open. I was reading from a serial to ethernet box called a Devicemaster. I changed the Devicemaster port setting from "connect always" to "connect on data" and the problem disappeared. I have great respect for Hans Passant but I do not agree that this is an error code that you can easily solve by scrutinizing code.

3

In my case the issue was caused by the fact that starting from .NET 5 or 6 you must either call async methods for async stream, or sync methods for sync strem. So that if I called FlushAsync I must have get context using GetContextAsync

Andrii
  • 1,081
  • 1
  • 11
  • 24
2

What I do when it happens is Disable the COM port into the Device Manager and Enable it again.

It stop the communications with another program or thread and become free for you.

I hope this works for you. Regards.

JD - DC TECH
  • 1,193
  • 9
  • 13
1

I ran into this error while using Entity Framework Core with Azure Sql Server running in Debug mode in Visual Studio. I figured out that it is an exception, but not a problem. EF is written to handle this exception gracefully and complete the work. I had VS set to break on all exceptions, so it did. Once I unchecked the check box in VS to not break on this exception, my C# code, calling EF, using Azure Sql worked every time.

MindModel
  • 822
  • 1
  • 10
  • 22
0

Ahh yes. Error 995 == 0x3E3. I've just stumbled across this while working with serial communications, and obtaining data with a parity error. There's an attribute in the DCB struct that is related to this behavior:

DCB::fAbortOnError == [TRUE | FALSE]

When configured as TRUE, and a parity error occurs in the RX data,

the driver terminates all read and write operations with an error status. The driver will not accept any further communications operations until the application has acknowledged the error by calling the ClearCommError function.

That's a quote from the Microsoft documentation on the DCB. The ABORT thing can actually happen on other errors as well, apart from parity... none of which I have experienced so far.

frr
  • 396
  • 3
  • 9