如何将HttpContext.Current传递给在.net中使用Parallel.Invoke()调用的方法

我有两个方法,它们使用HttpContext.Current来获取userID。 当我单独调用这些方法时,我得到userID,但是当使用Parallel.Invoke()调用相同的方法时,HttpContext.Current为null。

我知道原因,我只是在寻找可以访问HttpContext.Current的工作。 我知道这不是线程安全的,但我只想执行读操作

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"); } } } 

谢谢

存储对上下文的引用,并将其作为参数传递给方法…

像这样:

  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"); } }