本文介绍了如何将HttpContext.Current传递给在.net中使用Parallel.Invoke()调用的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两种使用HttpContext.Current来获取用户ID的方法.当我分别调用这些方法时,我获得了userID,但是当使用调用同一方法时Parallel.Invoke()HttpContext.Current为null.
I have two methods which makes use of HttpContext.Current to get the userID. When I call these method individually, I get the userID but when the same method is called usingParallel.Invoke() HttpContext.Current is 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");
}
}
}
谢谢
推荐答案
存储对上下文的引用,并将其作为参数传递给方法...
Store a reference to the context, and pass it to the methods as an argument...
赞:
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");
}
}
这篇关于如何将HttpContext.Current传递给在.net中使用Parallel.Invoke()调用的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!