2

我有一个具有以下两种方法的 .Net Webservice:

[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方法时,session不为null

场景 2)但是当我调用A时,在B中 session 和 HttpContext.Current 都是空的。

为什么?如何在第二种情况下启用B中的会话?如何访问 A 中的会话?我应该将其会话传递给 B 吗?如果是怎么办?

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

谢谢,

4

3 回答 3

0

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

请参阅http://forums.asp.net/t/1276840.aspxhttp://forums.asp.net/t/1630651.aspx/1

于 2012-07-11T12:11:44.130 回答
0
[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
}
于 2012-07-14T11:02:38.953 回答
-1

我必须使用一个全局字段:

/// <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;
}
于 2012-07-14T05:04:00.240 回答