Parallel.ForEach error HttpContext.Current

前端 未结 4 1438
猫巷女王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:13

    HttpContext.Current is null because it's running in "non-web threads". If you forked some code using new Thread(...) it would be exactly the same. The TPL somewhat hides this, but you still need to realize that each iteration in your Parallel.ForEach can potentially run in a different thread, and treat it accordingly.

    In particular, if you want to use some class or method out of the web request (and Parallel.ForEach is such an usage) you just can't use HttpContext.Current. A workaround is to explicitly pass the HttpContext (or HttpContextBase for improved testability) in the constructor (or as a method parameter)

    example :

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

提交回复
热议问题