简体   繁体   中英

How can I enable session in Threaded .Net Webservice?

I have a .Net Webservice with 2 following methods:

[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

scenario 2) but when I call A , in B both session and HttpContext.Current are null.

Why? How can I enable session in B in second scenario? How can I access the session in A? Should I pass its session to B? If yes how?

Method B should not have session as parameter.

Thanks,

It's because you're starting B in a new Thread.

See http://forums.asp.net/t/1276840.aspx or 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM