SqlCommand.CommandTimeout值被忽略

时间:2015-06-09 09:21:43

标签: c# .net sql-server-2012 sqlconnection sqlcommand

我尝试使用C#编写的Windows服务在SQL Server 2012上运行存储过程。该过程不返回任何数据,但需要很长时间才能执行,因此我将SqlCommand的CommandTimeout属性更改为5分钟。每当我运行代码时,我会在执行开始后的30秒内收到超时错误。有谁知道为什么我的价值被忽略了,还是我还忘了设置另一个超时?

app.config文件:

<configuration>
  <appSettings>
    <add key="myTimeout" value="600" />
  </appSettings>
  <connectionStrings>
    <add name="myConnectionString" connectionString=";data source=myServer,123456;Initial catalog=myDB;integrated security=SSPI;MultipleActiveResultSets=True;App=EntityFramework" />
  </connectionStrings>
</configuration>

代码:

var connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (var conn = new SqlConnection(connectionString))
{
    conn.Open();
    cmd = new SqlCommand("usp_myLongRunningOperation", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    // Change timeout if value present
    var commandTimeout = System.Configuration.ConfigurationManager.AppSettings["myTimeout"];
    int timeout;
    if (!string.IsNullOrEmpty(commandTimeout) && int.TryParse(commandTimeout, out timeout))
    {
        cmd.CommandTimeout = timeout;
    }

    cmd.ExecuteNonQuery();
}

(我已经单独测试了超时值解析,并正确设置了值)

0 个答案:

没有答案