2011-02-23 55 views
0

我正在調用客戶端的異步調用PageMethod。後端代碼是BeginInvoke方法和會話狀態

[WebMethod(EnableSession = true)] 
     public static string BeginMethodCall() 
     { //Session Accessible here 
      string g = Guid.NewGuid().ToString();      
      Func<object> f =() => MethodCall();     

      IAsyncResult asyncCall = f.BeginInvoke(null, f); 

      lock (AsyncThreadPool) 
       AsyncThreadPool[g] = asyncCall; 
      return g; 
     }    

     [WebMethod(EnableSession=true)] 
     public static object EndMethodCall(string guId) 
     { 
      IAsyncResult callResult; 
      lock (AsyncThreadPool) 
      { 
       callResult = AsyncThreadPool[guId]; 
       AsyncThreadPool.Remove(guId); 
      } 

      Func<object> f = (Func<object>)callResult.AsyncState; 
      callResult.AsyncWaitHandle.WaitOne(); 

      return f.EndInvoke(callResult); 
     } 

     [WebMethod(EnableSession = true)] 
     public static object MethodCall() 
     { 
      //Session not accessible here 
     } 

會話狀態是從BeginMethodCall()EndMethodCall()但不能從MethodCall()訪問。

有誰能告訴我爲什麼我在這裏失去我的會話狀態?

  1. 線程是否會丟失會話上下文,因爲asyn調用不是線程安全的?
  2. 有沒有辦法在此訪問會話?

回答

0

萬一有人可能會覺得這有用

的BeginXXX並創造了新的theard和線程不是出於顯而易見的原因

0

一般會話安全,

會議+異步=失敗

您在回調中並在分支到異步代碼之前是安全的,但在並行時,您不會獲得完整的會話狀態。

但是,有幾個解決方法。其中最容易的是

[SessionState(System.Web.SessionStateBehavior.ReadOnly)] 

在控制器級別,顯然它允許只讀訪問會話值。只要你不嘗試寫入會話,它將並行工作。你也可以實現你自己的HttpHandler,但那個更強硬一些。