Parallel.ForEach error HttpContext.Current

前端 未结 4 1432
猫巷女王i
猫巷女王i 2021-01-02 09:43

this method - doDayBegin(item.BranchId) is taking long time to execute. So I am using Parallel.ForEach to execute it parallel. When I am using norm

4条回答
  •  悲哀的现实
    2021-01-02 10:27

    Further adding to Bayu Alvian answer. I had a similar problem and I solved it by passing the context as parameter but inside the method I got

    Member 'method name' cannot be accessed with an instance reference

    I solved it by doing a little tweak from the above answer.

    // Get the new context
    HttpContext context = HttpContext.Current;
    Parallel.ForEach(items, item =>
        {
            DoSomething(context);
        }
    );
    
    private static void DoSomething(HttpContext context) {
     HttpContext.Current = context;
    }
    

    Assigning the context to the HttpContext.Current removes it.

提交回复
热议问题