2013-08-06 75 views
0

我需要爲特定的SqlCommand設置CommandTimeout屬性。前提是,主要連接字符串和SqlConnection正在使用不能更改。我喜歡定義超時值的可配置。想知道它的良好和公平的做法,以定義它在app.config(這是一個桌面應用程序)?從配置文件中定義SqlCommand.CommandTimeout

+0

有點主觀的問題,但我沒有看到它的問題。 –

+0

但是,您是否想要更改應用程序中使用的每個SqlCommand的超時時間或者只是爲了一個命令? – Steve

+0

@KevinDiTraglia而不是一個絕對的問題,它只是我的一個難題,並且想知道解決它的最佳方法:) – rageit

回答

3

app.config對於這種設置是一個很棒的地方。也許是這樣的:

<appSettings> 
    <add key="commandTimeout" value="2" /> 
</appSettings> 

然後,這將在一定的角度持續時間,基於你如何利用它。也許是這樣的:

var timeout = cnn.ConnectionTimeout; 
var configTimeout = ConfigurationManager.AppSettings["commandTimeout"]; 
if (!string.IsNullOrEmpty(configTimeout)) 
{ 
    timeout = Convert.ToInt32(configTimeout); 
} 

這當然可以存在於一個靜態類,這樣也許:

public static class AppSettings 
{ 
    private static int _commandTimeout = -1; 
    public static int CommandTimeout 
    { 
     get 
     { 
      if (_commandTimeout != -1) { return _commandTimeout; } 

      var configTimeout = ConfigurationManager.AppSettings["commandTimeout"]; 
      if (!string.IsNullOrEmpty(configTimeout)) 
      { 
       _commandTimeout = Convert.ToInt32(configTimeout); 
      } 
      else 
      { 
       _commandTimeout = 1; // this is the default if the setting doesn't exist 
      } 

      return _commandTimeout; 
     } 
    } 
} 

然後,所有你需要做的是:

var timeout = AppSettings.CommandTimeout; 

或者更簡潔:

cmd.CommandTimeout = AppSettings.CommandTimeout; 
+0

SqlCommand.CommandTimeout屬性的默認超時是30秒:) – rageit

+0

@rageit,這是真的,我只是把數字投入我的例子。 –

0

你c在應用程序配置文件中使用CommandTimeout屬性和Time Paramater。

connection = Factory.CreateConnection(); 
connection.ConnectionString = ConnectionString.ConnectionString; 
connection.Open(); 

this.cmd = connection.CreateCommand(); 
cmd.CommandTimeout = ConfigurationManager.AppSettings["TimeConfigParam"];