2012-07-11 19 views
2

我有一個NET Web服務用2種以下方法:如何在Threaded .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)但是當我請致電AB會話和HttpContext.Current都爲空。

爲什麼?如何在第二種情況下啓用B中的會話?我如何訪問A中的會話?我應該把它的會議通過B嗎?如果是的話如何?

方法B不應該有會話作爲參數。

謝謝,

回答

-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; 
} 
+0

而當A()被調用兩次(和B()被調用兩次) ,這兩個B()調用都具有相同的會話。這是非常非常錯誤的。 – TcKs 2012-07-14 11:00:57

+0

請詳細解釋。什麼是兩次B()調用的問題。 – breceivemail 2012-07-14 12:14:34

+0

如果它被相同的客戶端調用,它總是具有相同的會話。 – breceivemail 2012-07-14 12:15:47

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 
}