Search code examples
c#asp.nettask-parallel-libraryhttpcontext

How to pass HttpContext.Current to methods called using Parallel.Invoke() in .net


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


Solution

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