我有两种利用 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");
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)