如何在Threaded.Net Web服务中启用会话



我有一个.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;
}

场景1)当我直接调用B方法时,会话不是空

场景2)但当我调用A时,在B中,会话和HttpContext.Current都为null。

为什么?在第二种情况下,如何在B中启用会话?如何访问A中的会话?我应该把会议交给B吗?如果是,如何?

方法B不应将会话作为参数。

谢谢,

这是因为您正在一个新线程中启动B。

请参阅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
}

我必须使用全局字段:

/// <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;
}

最新更新