Npgsql Error: exception while reading from stream in Asp.net Core

Dung Do Tien May 07 2021 218

I have a project web using Asp.Net, PostgreSQL and I using Dapper to help connect to the database.

I have a function to get some keyword from the database as below:

 public List<KeywordInfoEntity> GetTopKeyword(KeywordOnPageEntity objKeywordOnPage, int top)
{
    List<KeywordInfoEntity> lstKeywordInfo = null;
    try
    {
        using (PostgresSQL db = new PostgresSQL())
        {
            using (NpgsqlCommand command = db.CreateCommand("func_get_keywordonpage", true))
            {
                command.Parameters.Add(new NpgsqlParameter("@_regionid", objKeywordOnPage.RegionId));
                command.Parameters.Add(new NpgsqlParameter("@_top", top));
                
                using (NpgsqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        lstKeywordInfo = new List<KeywordInfoEntity>();
                        KeywordInfoEntity objKeyword;
                        while (reader.Read())
                        {
                            objKeyword = new KeywordInfoEntity();
                            objKeyword.Name = reader.GetString(0);
                            objKeyword.Link = reader.GetString(1);
                            lstKeywordInfo.Add(objKeyword);
                        }
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        Logger.ErrorLog(ex);
    }
    return (lstKeywordInfo);
}

When running this method to get data. I got an error Npgsql.NpgsqlException (0x80004005): Exception while reading from stream

 Npgsql.NpgsqlException (0x80004005): Exception while reading from stream ---> System.IO.IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   --- End of inner exception stack trace ---
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at Npgsql.NpgsqlReadBuffer.<>c__DisplayClass31_0.<<Ensure>g__EnsureLong|0>d.MoveNext()
   at Npgsql.NpgsqlReadBuffer.<>c__DisplayClass31_0.<<Ensure>g__EnsureLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Npgsql.NpgsqlConnector.<>c__DisplayClass161_0.<<ReadMessage>g__ReadMessageLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Npgsql.NpgsqlDataReader.<NextResult>d__46.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Npgsql.NpgsqlDataReader.NextResult()
   at Npgsql.NpgsqlCommand.<ExecuteDbDataReader>d__100.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at Npgsql.NpgsqlCommand.ExecuteReader()

I really can't understand what's the reason.

Please tell me why how to resolve it.

Have 1 answer(s) found.
  • N

    Nguyễn Minh Đạt May 08 2021

    This issue usually occurs when your server full and response slow.

    Please check how is your CPU and RAM, If it's full you can you can do as below to find why the Npgsql server take more CPU.

    1. Check which database name is taking most CPU .

    You can run the command below:

     SELECT usename, datname, COUNT(1)
    FROM pg_stat_activity
    GROUP BY usename, datname

    See count column you can know database name has the most activity.

    exception while reading from stream

    2. Get query executed most times in that database

    you can run the command below:

     SELECT query, count(*)  FROM pg_stat_activity where  usename= 'user_db_name' 
    group by query 

    you can see the result below, and see what's command is execute most times.

    exception while reading from stream

    From this command, you can check it in your project code, maybe you called it in a loop. Have much traffic access but you not use cache or have many cases here. You have to reduce connect to the database to fix these issues

    I got the same error and I tracking as above and I resolved it.

    Hope helpful for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close