2013-05-08 18 views
6

Mam dwie metody, które używa HttpContext.Current, aby uzyskać identyfikator użytkownika. Gdy wywołuję tę metodę indywidualnie, otrzymuję identyfikator użytkownika, ale gdy ta sama metoda jest wywoływana przy użyciu Parallel.Invoke() HttpContext.Current ma wartość null.Jak przekazać HttpContext.Current do metod wywoływanych przy użyciu Parallel.Invoke() w .net

Znam powód, po prostu szukam pracy wokół przy użyciu, które można uzyskać dostęp HttpContext.Current. Wiem, że to nie jest wątku bezpieczne, ale chcę tylko do wykonywania operacji odczytu

public partial class _Default : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      Display(); 
      Display2(); 
      Parallel.Invoke(Display, Display2); 
     } 

     public void Display() 
     { 
      if (HttpContext.Current != null) 
      { 
       Response.Write("Method 1" + HttpContext.Current.User.Identity.Name); 
      } 
      else 
      { 
       Response.Write("Method 1 Unknown"); 
      } 
     } 

     public void Display2() 
     { 

      if (HttpContext.Current != null) 
      { 
       Response.Write("Method 2" + HttpContext.Current.User.Identity.Name); 
      } 
      else 
      { 
       Response.Write("Method 2 Unknown"); 
      } 
     } 
    } 

Dziękuję

Odpowiedz

5

przechowywać odniesienia do kontekstu, i przekazać je do metod jako argument ...

W ten sposób:

protected void Page_Load(object sender, EventArgs e) 
    { 
     var ctx = HttpContext.Current; 
     System.Threading.Tasks.Parallel.Invoke(() => Display(ctx),() => Display2(ctx)); 
    } 

    public void Display(HttpContext context) 
    { 
     if (context != null) 
     { 
      Response.Write("Method 1" + context.User.Identity.Name); 
     } 
     else 
     { 
      Response.Write("Method 1 Unknown"); 
     } 
    } 

    public void Display2(HttpContext context) 
    { 

     if (context != null) 
     { 
      Response.Write("Method 2" + context.User.Identity.Name); 
     } 
     else 
     { 
      Response.Write("Method 2 Unknown"); 
     } 
    }