0

CommandTimeout特定の のプロパティを設定する必要がありSqlCommandます。前提は、メインの接続文字列とSqlConnection使用されているものを変更できないことです。タイムアウト値の定義を構成可能にするのが好きです。app.config でそれを定義することが適切で公正な方法であるかどうかを知りたいですか (これはデスクトップ アプリです)。

4

3 に答える 3

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;
于 2013-08-06T17:41:25.233 に答える
0

TimeSpan を AppConfig オプション値のタイプとして使用して、@ mike-perrenoud の回答を拡張します。さらに調整するために、より読みやすく、理解しやすくなっています。Project Propertiesオプションは->経由で追加できますSettings tab。コードが望むように

SqlCommand command = connection.CreateCommand();
command.CommandTimeout = (int)Properties.Settings.Default.SqlCommandTimeout.TotalSeconds;

app.config

<setting name="SqlCommandTimeout" serializeAs="String">
  <value>00:05:00</value>
</setting>

プロパティ/Settings.settings

// generated by VS
<Setting Name="SqlCommandTimeout" Type="System.TimeSpan" Scope="Application">
  <Value Profile="(Default)">00:05:00</Value>
</Setting>

プロパティ/Settings.Designer.cs

// generated by VS
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("00:05:00")]
public global::System.TimeSpan SqlCommandTimeout {
  get {
    return ((global::System.TimeSpan)(this["SqlCommandTimeout"]));
  }
 }
于 2018-12-12T15:09:36.777 に答える