I am reading a bunch of queries from a database. I had an issue with the queries not closing, so I added a CommandTimeout. Now, the individual queries read from the config file each time they are run. How would I make the code cache the int from the config file only once using a static nullable and getter. I was thinking of doing something along the lines of:

static int? var;
get{ var = null;
    if (var.HasValue)
    ...(i dont know how to complete the rest)

My actual code:

private object QueryMethod(string item)
{
    using (SqlConnection connection = new SqlConnection(item))
    {
        connection.Open();

        using (SqlCommand sql = new SqlCommand())
        {
            AddSQLParms(sql);
            sql.CommandTimeout = 30;
            sql.CommandText = _cmdText;
            sql.Connection = connection;
            sql.CommandType = System.Data.CommandType.Text;

            sql.ExecuteNonQuery();
        }
        connection.Close();
    }
    return false;
}
有帮助吗?

解决方案 3

var is a system keyword - don't use it

V1 - in this version you expect config to have a value, otherwise error will occur

static int? _timeout = null;

private static int GetTimeout()
{
    if (_timeout != null) return (int)_timeout;
    _timeout = GetTimeoutFromConfig();
    return (int)_timeout;
}

V2 - in this version you will use default value if config is empty

static int? _timeout = null;
private const int def_timeout = 120;   

private static int GetTimeout()
{
    if (_timeout != null) return (int)_timeout;
    int? to = GetTimeoutFromConfig();
    _timeout = (to ?? def_timeout); 

    return (int)_timeout;
}

converting from config

private int? GetTimeoutFromConfig()
{
    int val;
    bool converted = int.TryParse(ConfigurationManager.AppSettings["TimeoutValue"], out val);

    return (converted ? val : null);
} 

其他提示

First: don't call it var !

Let's call it cached_value.

static int? cached_value;

get { return cached_value ?? cached_value = your_logic_here }

This way, the first time you call it, if it's null, it'll initialize the field. Next time you call the getter, you'll just get the value you need.

You could try something like this utilizing the Lazy<T> class:

public static class ConfigCache
{
    private static Lazy<int> connectionTimeout =
        new Lazy<int>(() => int.Parse(
            ConfigurationManager.AppSettings["connectionTimeout"]));

    public static int ConnectionTimeout
    {
        get { return connectionTimeout.Value; }
    }
}

Usage:

sqlCmd.CommandTimeout = ConfigCache.ConnectionTimeout;

It sounds to be like you're asking how to use a Nullable variable.

static int? val;
get{ 
    if (var.HasValue)
    {
      return val.Value;
    }
    else {
       val = GetValFromConfig();
       return val.Value;
    }
} 

var is a keyword in C#

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top