[英]How can I enable session in Threaded .Net Webservice?
我有一種使用以下兩種方法的.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方法時,會話不為null
場景2),但是當我在B中調用A時 ,session和HttpContext.Current均為null。
為什么? 在第二種情況下,如何在B中啟用會話? 如何訪問A中的會話? 我應該將其會話傳遞給B嗎? 如果是,怎么辦?
方法B不應將會話作為參數。
謝謝,
這是因為您正在新線程中啟動B。
參見http://forums.asp.net/t/1276840.aspx或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
}
我必須使用一個全局字段:
/// <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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.