Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 820
SharpCoder Avatar asked May 08 '13 08:05

SharpCoder


Video Answer


1 Answers

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");
        }
    }
like image 80
Skymt Avatar answered Oct 04 '22 02:10

Skymt