How to pass HttpContext.Current to methods called

2019-04-29 03:33发布

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 using Parallel.Invoke() HttpContext.Current is null.

I know the reason, I am just looking for work around using which I can access HttpContext.Current. I know this is not thread safe but I only want to perform read operation

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

Thank you

1条回答
迷人小祖宗
2楼-- · 2019-04-29 04:02

Store a reference to the context, and pass it to the methods as an argument...

Like this:

    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");
        }
    }
查看更多
登录 后发表回答