我的项目有个留言短信发送模块,是用多线程方式实现的,同时对每条发送短信的记录写入数据库,意思就是在多线程下调用操作数据库。
ORM是ibatis. net 在select或insert操作的时候出现了这个异常WebSessionStore: Could not obtain reference to HttpContext。其他操作没测试过,应该都是提示同样的错误。
发送方法代码:
private void SendMessage(object i)
{
string Mobile = MobileList[(int)i];
mutex.WaitOne();
SMSSystem.Send(Mobile, MessageContent);
CommonHelper.WriteLog(EventFlag.InviterCommentsSMSSend, "留言提醒发送到了手机号:" + Mobile, SiteMaster);
mutex.ReleaseMutex();
}
WriteLog()是CommonHelper类的静态方法。下面我贴上WriteLog()代码
public static void WriteLog(EventFlag Event, string Detail, Dictionary<string, string> sitemaster)
{
try
{
EventLog Model = new EventLog();
EventLogDao EventDao = new EventLogDao();
Model.UserId = Convert.ToInt32(sitemaster["UserId"]);
Model.EventNum = (short)Event;
Model.Detail = Detail;
Model.Creator = sitemaster["UserName"];
Model.AddIP = sitemaster["LoginIP"];
EventDao.Insert(Model);
}
catch(Exception Ex)
{
throw new Exception(Ex.Message);
}
}
我把ibatis 的insert()方法也贴上吧,这是codesmith生成的,应该没问题,而且如果我不在多线程下调用的时候也没问题
public void Insert(EventLog obj) {
if (obj == null) throw new ArgumentNullException("obj");
String stmtId = "EventLog.Insert";
InvestmentMapper.Get().Insert(stmtId, obj);
}
劳烦各位高手了,小弟不胜感激!
因为ibatis的ISqlMapSession是存储在Http.Request.Items上的,在你新开的线程里是不能操作IIS的上的线程的,根据ibatis的文档上说的,可以用:HybridWebThreadSessionStore
The DatatMapper component store his working ISqlMapSession on different session store.
On Web environnement, the session is stored Http.Request.Items.
On windows environnement on the current thread.
You can configure the session storage by specifing the property ISessionStore on ISqlMapper.
This will allow to set a custom session store like the HybridWebThreadSessionStore This is used for scenarios where most of the you need per request session, but you also does some work outside a request (in a thread pool thread, for instance).
Set it after the configuration and before use of the ISqlMapper.