【发布时间】:2011-11-04 05:37:56
【问题描述】:
我对这些技术还是很陌生。这里真正的问题是如何在控制台应用程序中管理每个线程的会话。目前,如果我将它作为单个线程运行,那么一切都很好。一旦我切换到多线程模型,我就会开始看到会话级别的争用(因为 Session 对象在设计上不是安全的)KeyNotFound 异常(以及其他)开始被抛出。
在网络应用中,你会做这样的事情:
/// <summary>
/// Due to issues on IIS7, the NHibernate initialization cannot reside in Init() but
/// must only be called once. Consequently, we invoke a thread-safe singleton class to
/// ensure it's only initialized once.
/// </summary>
protected void Application_BeginRequest(object sender, EventArgs e)
{
NHibernateInitializer.Instance().InitializeNHibernateOnce(
() => InitializeNHibernateSession());
}
/// <summary>
/// If you need to communicate to multiple databases, you'd add a line to this method to
/// initialize the other database as well.
/// </summary>
private void InitializeNHibernateSession()
{
var path = ConfigurationManager.AppSettings["NHibernateConfig"];
NHibernateSession.Init(
webSessionStorage,
new string[] { Server.MapPath("~/bin/foo.Data.dll") },
new AutoPersistenceModelGenerator().Generate(),
Server.MapPath("~/App_Configuration/" + path ));
}
// sample of my console app... very simple
static void Main(string[] args)
{
InitializeNHibernateSession();
while(true)
{
Task.Factory.StartNew(() => SomeAwesomeLongRunningPieceOfWork());
}
}
这实质上是在 global.asax 中的每个线程(网络请求)执行一次初始化。
关于如何在控制台应用程序中设置此(会话管理)的任何想法?
【问题讨论】:
-
大概是在控制台应用程序中您自己管理线程?当然,您创建的线程具有可以调用初始化方法的入口点,与 Application_BeginRequest 相同。如果我们有更多关于您如何在控制台应用程序中管理线程的信息将会很有帮助:)
-
@MattDavey - 我将更新 OP 以反映我的设置。
标签: c# .net nhibernate console-application sharp-architecture