如何强制Npgsql在ASP.NET MVC3应用程序中使用连接字符串中的CommandTimeout值

时间:2013-09-25 09:40:17

标签: asp.net asp.net-mvc asp.net-mvc-3 mono npgsql

ASP.NET MVC3应用程序使用npgsql 2.0.12.0通过mod_mono在Mono中获取数据。 有时会发生以下超时异常。如果发生异常,请求持续时间为31秒。

使用

将连接字符串中的CommandTimeout设置为5分钟
        NpgsqlConnectionStringBuilder csb = new NpgsqlConnectionStringBuilder()
        {
            CommandTimeout = 5*60,  // 5 min
            Host = Config.Server,
            Database = Config.DefaultDataBase,
            UserName = Config.ServerUser,
            Port = Config.Port,
            SslMode = SslMode.Prefer,
            SSL = true,
        };

如何强制npgsql使用超时5分钟而不是在31秒后抛出激活? 在postgresql.con文件中没有设置statement_timeout,因此它不会来自服务器。

使用ExecuteReader执行查询:

        using (IDbConnection conn = DataAccessBase.CreateConnection())
        using (IDbCommand cmd = conn.CreateCommand())
        {
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = string.Format(command, paramNames);
            conn.Open();
            using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SingleResult))
            {
                if (reader.Read())
                {
                    string[] names = new string[reader.FieldCount];
                    for (int i = 0; i < names.Length; i++)
                    {
                        names[i] = reader.GetName(i);
                    }
                    Func<IDataRecord, MyDataContext, T> objInit = InitializerCache<T>.GetInitializer(names, ConvertValue != null);
                    do
                    { // walk the data 
                        yield return objInit(reader, this);
                    } while (reader.Read());
                }
                while (reader.NextResult()) { } // ensure any trailing errors caught 
            }
        }

从请求开始31秒后发生异常。

请求标题:

Connection  Keep-alive
Accept  */*
Accept-Encoding gzip,deflate
From    googlebot(at)googlebot.com
User-Agent  Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)

例外:

Npgsql.NpgsqlException:
A timeout has occured. If you were establishing a connection, increase Timeout value in ConnectionString. If you were executing a command, increase the CommandTimeout value in ConnectionString or in your NpgsqlCommand object.
  at Npgsql.NpgsqlState.ProcessBackendResponsesEnum (Npgsql.NpgsqlConnector context) [0x00000] in <filename unknown>:0 
  at Npgsql.NpgsqlReadyState.QueryEnum (Npgsql.NpgsqlConnector context, Npgsql.NpgsqlCommand command) [0x00000] in <filename unknown>:0 
  at Npgsql.NpgsqlConnector.QueryEnum (Npgsql.NpgsqlCommand queryCommand) [0x00000] in <filename unknown>:0 
  at Npgsql.NpgsqlCommand.GetReader (CommandBehavior cb) [0x00000] in <filename unknown>:0 
  at Npgsql.NpgsqlCommand.ExecuteReader (CommandBehavior cb) [0x00000] in <filename unknown>:0 

1 个答案:

答案 0 :(得分:-3)

抱歉,我认为您的CommandTime不正确:

CommandTimeout = 5*60, // 5 min

是30秒(300毫秒)。