我正在尝试创建一个负责读取所有用户访问设置的对象。
我这样创建了类:
public class SettingsManager
{
private static string _connString =
@"Data Source=MyDB;Initial Catalog=IT;Integrated Security=True;Asynchronous Processing=true;";
private const string _spName = "SettingTest";
private IEnumerable<string> _mySettings;
private static readonly Lazy<SettingsManager> _instance = new Lazy<SettingsManager>(() => new SettingsManager());
private SettingsManager()
{
//Console.WriteLine("Hello from constructor");
if (_mySettings == null)
_mySettings = ReadSettings();
}
public static SettingsManager Instance
{
get { return _instance.Value; }
}
public bool CanDo(string setting)
{
return _mySettings.Contains(setting);
}
private IEnumerable<string> ReadSettings()
{
try
{
using (var conn = new SqlConnection(_connString))
{
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = _spName;
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
using (var reader = cmd.ExecuteReader())
{
return reader.Select(SettingParser).ToList();
}
}
}
}
catch
{
}
return null;
}
private string SettingParser(SqlDataReader r)
{
try
{
return r[0] is DBNull ? null : r[0].ToString();
}
catch
{
}
return null;
}
}
和 SqlDataReader 扩展
public static class DBExtensions
{
public static IEnumerable<T> Select<T>(
this SqlDataReader reader, Func<SqlDataReader, T> projection)
{
while (reader.Read())
{
yield return projection(reader);
}
}
}
然后在我的应用程序中,我可以这样称呼它:
SettingsManager.Instance.CanDo("canWrite")
这返回真/假值取决于用户访问级别。
我的问题是:
这个线程安全吗?数据库是否有可能被多次查询?如何防止这种情况?
我应该使用等待和异步吗?我只查询 db 一次。我该如何改进呢?(await 和 async 对我来说真的很新,因为我刚从 .NET3.5 迁移到 4.5)