ASP.NET,会话中存储的线程和连接字符串
ASP.NET, thread and connection-string stored in Session
我的应用程序可以连接多个数据库(每个数据库都有相同的架构),我将用户选择的当前数据库存储在会话中,并使用静态 属性 封装访问,例如:
public class DataBase
{
public static string CurrentDB
{
get
{
return HttpContext.Current.Session["CurrentDB"].ToString();
}
set
{
HttpContext.Current.Session["CurrentDB"] = value;
}
}
}
其他代码段访问静态 CurrentDB 以确定使用什么数据库。
一些操作在线程中启动后台进程,它需要访问 CurrentDB 来做一些事情。我正在考虑使用这样的东西:
[ThreadStatic]
private static string _threadSafeCurrentDB;
public static string CurrentDB
{
get
{
if (HttpContext.Current == null)
return _threadSafeCurrentDB;
return HttpContext.Current.Session["CurrentDB"].ToString();
}
set
{
if (HttpContext.Current == null)
_threadSafeCurrentDB = value;
else
HttpContext.Current.Session["CurrentDB"] = value;
}
}
并像这样启动线程:
public class MyThread
{
private string _currentDB;
private thread _thread;
public MyThread (string currentDB)
{
_currentDB = currentDB;
_thread = new Thread(DoWork);
}
public DoWork ()
{
DataBase.CurrentDB = _currentDB;
... //Do the work
}
}
这是一种不好的做法?
实际上,我认为您应该能够确定哪个线程使用哪个数据库,因此我会创建一个继承自 Thread
的 class
,但要知道它使用的数据库。它应该有一个 getDB()
方法,因此,如果您需要一个 new Thread
将使用与另一个特定 Thread
中使用的相同的数据库,您可以使用它。您也应该能够 setDB(db)
of a Thread
。
在会话中,您使用的是当前数据库方法,该方法假定只有一个当前数据库。如果这个假设描述了事实,那么您可以保持原样并在使用新的当前数据库时更新它。如果您必须同时使用多个数据库,那么您可能想要一个 Dictionary
数据库,其中 Value
是数据库,Key
是某种数据库具有语义含义的代码,您可以使用它来确定在哪里需要哪个实例。
我的应用程序可以连接多个数据库(每个数据库都有相同的架构),我将用户选择的当前数据库存储在会话中,并使用静态 属性 封装访问,例如:
public class DataBase
{
public static string CurrentDB
{
get
{
return HttpContext.Current.Session["CurrentDB"].ToString();
}
set
{
HttpContext.Current.Session["CurrentDB"] = value;
}
}
}
其他代码段访问静态 CurrentDB 以确定使用什么数据库。
一些操作在线程中启动后台进程,它需要访问 CurrentDB 来做一些事情。我正在考虑使用这样的东西:
[ThreadStatic]
private static string _threadSafeCurrentDB;
public static string CurrentDB
{
get
{
if (HttpContext.Current == null)
return _threadSafeCurrentDB;
return HttpContext.Current.Session["CurrentDB"].ToString();
}
set
{
if (HttpContext.Current == null)
_threadSafeCurrentDB = value;
else
HttpContext.Current.Session["CurrentDB"] = value;
}
}
并像这样启动线程:
public class MyThread
{
private string _currentDB;
private thread _thread;
public MyThread (string currentDB)
{
_currentDB = currentDB;
_thread = new Thread(DoWork);
}
public DoWork ()
{
DataBase.CurrentDB = _currentDB;
... //Do the work
}
}
这是一种不好的做法?
实际上,我认为您应该能够确定哪个线程使用哪个数据库,因此我会创建一个继承自 Thread
的 class
,但要知道它使用的数据库。它应该有一个 getDB()
方法,因此,如果您需要一个 new Thread
将使用与另一个特定 Thread
中使用的相同的数据库,您可以使用它。您也应该能够 setDB(db)
of a Thread
。
在会话中,您使用的是当前数据库方法,该方法假定只有一个当前数据库。如果这个假设描述了事实,那么您可以保持原样并在使用新的当前数据库时更新它。如果您必须同时使用多个数据库,那么您可能想要一个 Dictionary
数据库,其中 Value
是数据库,Key
是某种数据库具有语义含义的代码,您可以使用它来确定在哪里需要哪个实例。