【问题标题】:How can I enable session in Threaded .Net Webservice?如何在 Threaded .Net Webservice 中启用会话?
【发布时间】:2012-07-14 19:02:38
【问题描述】:

我有一个具有以下两种方法的 .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方法时,session不为空

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

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

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

谢谢,

【问题讨论】:

    标签: c# .net web-services session


    【解决方案1】:

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

    http://forums.asp.net/t/1276840.aspx 或者 http://forums.asp.net/t/1630651.aspx/1

    【讨论】:

      【解决方案2】:
      [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
      }
      

      【讨论】:

        【解决方案3】:

        我必须使用全局字段:

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

        【讨论】:

        • 当 A() 被调用两次(并且 B() 被调用两次)时,两个 B() 调用具有相同的会话。这是非常非常错误的。
        • 请多解释。两次 B() 调用有什么问题。
        • 如果它被同一个客户端调用,它总是有相同的会话。
        • 但是您没有任何保证,呼叫总是由同一个客户拨打。如果是这样 - 这只是巧合,但这个概念完全是错误的。
        • 对于每个客户端(会话)CurrentSession 是不同的。学习会话和应用程序生命周期。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        • 2012-09-11
        • 1970-01-01
        相关资源
        最近更新 更多