如何在Threaded .Net Webservice中启用会话?

时间:2012-07-11 12:04:32

标签: c# .net web-services session

我有一个.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 方法时,会话不为空

方案2)但是当我打电话给 A 时,在 B 中,会话和HttpContext.Current都为空。

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

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

谢谢,

3 个答案:

答案 0 :(得分:0)

这是因为你在一个新线程中开始了B.

参见http://forums.asp.net/t/1276840.aspx 要么 http://forums.asp.net/t/1630651.aspx/1

答案 1 :(得分: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
}

答案 2 :(得分:-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;
}