使用SqlCommand执行存储过程时如何防止超时错误?

osh*_*nen 15 .net c# sql-server sqlclient

我有一个运行存储过程的C#程序.如果我从Microsoft SQL Server管理工作室运行存储过程,它工作正常.执行大约需要30秒.但是,如果我尝试从C#程序运行相同的存储过程,它会超时,即使我已将连接字符串中的超时设置为10分钟.

using (connection1 = new SqlConnection("user id=user_id_goes_here;password=password_goes_here;initial catalog=database_name_goes_here;data source=server_name_goes_here;connection timeout=600))
Run Code Online (Sandbox Code Playgroud)

它似乎在大约30秒后超时,即使我已将其设置为允许10分钟(用于测试目的).

Pat*_*ood 23

连接超时仅用于连接数据库.

该类有一个单独的CommandTimeout属性SqlCommand,使用此属性指定执行超时.

IE浏览器.

using (SqlCommand cmd = new SqlCommand())
{
  cmd.Connection = connection1;
  cmd.CommandTimeout = 240; //in seconds
  //etc...
}
Run Code Online (Sandbox Code Playgroud)

  • 如果使用0,则表示没有限制. (5认同)
  • 只是要指出这只是问题的"乐队援助".最好通过解决潜在问题来弄清楚为什么你首先得到超时. (2认同)

And*_*yev 6

使用SqlCommand.CommandTimeout命令的属性而不是在连接字符串中指定它.

请参阅MSDN以供参考.