[英]How can I enable session in Threaded .Net Webservice?
I have a .Net Webservice with 2 following methods: 我有一种使用以下两种方法的.Net Web服务:
[WebMethod(EnableSession = true)]
public void A()
{
HttpSessionState session = Session;
Thread thread = new Thread(B);
thread.Start();
}
[WebMethod(EnableSession = true)]
public void B()
{
HttpSessionState session = Session;
}
scenario 1) When I call B method directly, session is not null 情况1)当我直接调用B方法时,会话不为null
scenario 2) but when I call A , in B both session and HttpContext.Current are null. 场景2),但是当我在B中调用A时 ,session和HttpContext.Current均为null。
Why? 为什么? How can I enable session in B in second scenario?
在第二种情况下,如何在B中启用会话? How can I access the session in A?
如何访问A中的会话? Should I pass its session to B?
我应该将其会话传递给B吗? If yes how?
如果是,怎么办?
Method B should not have session as parameter. 方法B不应将会话作为参数。
Thanks, 谢谢,
It's because you're starting B in a new Thread. 这是因为您正在新线程中启动B。
See http://forums.asp.net/t/1276840.aspx or http://forums.asp.net/t/1630651.aspx/1 参见http://forums.asp.net/t/1276840.aspx或http://forums.asp.net/t/1630651.aspx/1
[WebMethod(EnableSession = true)]
public void A()
{
HttpSessionState session = Session;
Action action = () => B_Core(session);
Thread thread = new Thread(action);
thread.Start();
}
[WebMethod(EnableSession = true)]
public void B()
{
HttpSessionState session = Session;
B_Core(session);
}
private void B_Core(HttpSessionState session)
{
// todo
}
I have to use a global field: 我必须使用一个全局字段:
/// <summary>
/// Holds the current session for using in threads.
/// </summary>
private HttpSessionState CurrentSession;
[WebMethod(EnableSession = true)]
public void A()
{
CurrentSession = Session;
Thread thread = new Thread(B);
thread.Start();
}
[WebMethod(EnableSession = true)]
public void B()
{
//for times that method is not called as a thread
CurrentSession = CurrentSession == null ? Session : CurrentSession;
HttpSessionState session = CurrentSession;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.