在ASP.NET MVC中执行SQL Server存储过程时,如何防止超时错误?

时间:2018-12-31 11:57:08

标签: sql-server asp.net-mvc-4 stored-procedures

我有一个C#ASP.NET MVC程序,该程序在加载页面时运行存储过程。如果我从Microsoft SQL Server Management Studio运行存储过程,则需要1分钟。但是,如果我尝试从代码运行相同的存储过程,则会超时。 我在web.config中添加了Connection Timeout = 0,但是有时它可以工作,有时却不能。

1 个答案:

答案 0 :(得分:1)

调用存储过程时,可以将“超时命令”设置为0。

using (SqlConnection connection = new SqlConnection(connectionString)) 
{
   connection.Open();  
   SqlCommand cmd= new SqlCommand(queryString, connection);  
   // Setting command timeout to 0 second  
   cmd.CommandTimeout = 0;  
   try 
   {  
     cmd.ExecuteNonQuery(); 
   }  
   catch(Exception ex)
   {
      // log ex here
   }
}