6

HttpContext.Current を使用してユーザー ID を取得する 2 つのメソッドがあります。これらのメソッドを個別に呼び出すと、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");
            }
        }
    }

ありがとうございました

4

1 に答える 1

5

コンテキストへの参照を保存し、引数としてメソッドに渡します...

このような:

    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");
        }
    }
于 2013-05-08T10:49:37.900 に答える