【问题标题】:How to pass HttpContext.Current to methods called using Parallel.Invoke() in .net如何将 HttpContext.Current 传递给在 .net 中使用 Parallel.Invoke() 调用的方法
【发布时间】:2013-05-08 08:27:13
【问题描述】:

我有两种方法使用 HttpContext.Current 来获取用户 ID。当我单独调用这些方法时,我得到了用户 ID,但是当使用相同的方法调用时 Parallel.Invoke() HttpContext.Current 为空。

我知道原因,我只是在寻找可以访问 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");
            }
        }
    }

谢谢

【问题讨论】:

    标签: c# asp.net task-parallel-library httpcontext


    【解决方案1】:

    存储对上下文的引用,并将其作为参数传递给方法...

    像这样:

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

    【讨论】:

      猜你喜欢
      • 2011-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多