ForEach错误HttpContext

ForEach错误HttpContext

本文介绍了Parallel.ForEach错误HttpContext.Current的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此方法 - doDayBegin(item.BranchId)需要很长时间才能执行。所以我使用 Parallel.ForEach 来执行它并行。当我使用正常的 foreach 循环它的工作正常,但是当我使用 Parallel.ForEach 它显示这个错误
$
对象引用未设置为对象的实例。

  public ActionResult Edit([DataSourceRequest] DataSourceRequest请求)
{
try
{
JavaScriptSerializer js = new JavaScriptSerializer();
列表< DB0010020Vm> _listDB0010020Vm =新列表< DB0010020Vm>();

string dataDB0010020vm = Request.Form [griddetailsvm];
if(!string.IsNullOrEmpty(dataDB0010020vm))
{
_listDB0010020Vm = js.Deserialize< List< DB0010020Vm>(dataDB0010020vm)。
其中(d => d.IsValid ==YES)ToList();
}
DateTime start = DateTime.UtcNow;


Parallel.ForEach(_listDB0010020Vm,item =>
{
doDayBegin(item.BranchId);
});

DateTime end = DateTime.UtcNow;
TimeSpan duration = end-start;
return Json(new
{
success = true,
message =Day Begin Process Successful successfully successfully!+ duration
});
}
catch(Exception e)
{
return Json(new
{
success = false,
message = e.Message
});

}
}

public void doDayBegin(int BranchId)
{
var httpContext = System.Web.HttpContext.Current;
IDB0010020Repository _idDB0010020Repository = new DB0010020Repository();
IDB0010044Repository _idDB0010044Repository = new DB0010044Repository();

EBS.DAL.Model.DB0010020 branchDetails = _idDB0010020Repository.FindOne(d => d.BranchId == BranchId);
if(branchDetails == null)
{
ModelState.AddModelError(,Branch not found!);
}
else
{
try
{
DateTime LastOpenDate = DateTime.ParseExact(Request.Form [LastOpenDate] ToString(), dd / MM / yyyy,CultureInfo.InvariantCulture);
// branchDetails.LastOpenDate = LastOpenDate;
// branchDetails.LastOpenDate = Convert.ToDateTime(Request.Form [LastOpenDate]。ToString());


}
catch(异常e)
{
// branchDetails.LastOpenDate = Convert.ToDateTime(2014-07-25 00:00 :00.000\" );
}


OperationStatus status = _idDB0010020Repository.UpdateAndSave(branchDetails);
if(status!= null&!status.Status)
ModelState.AddModelError(Updation failed,status.ExceptionMessage);
}

EBS.DAL.Model.DB0010044 dayBegin = new DB0010044();
dayBegin.BankId = 1;
dayBegin.BranchId = BranchId;
dayBegin.DayBeginFlag = 1;
//添加d
DateTime DayDate = DateTime.ParseExact(Request.Form [LastOpenDate]。ToString(),dd / MM / yyyy,CultureInfo.InvariantCulture);
dayBegin.DayDate = DayDate;
//添加d

// dayBegin.DayDate = Convert.ToDateTime(Request.Form [LastOpenDate]);
dayBegin.DayEndFlag = 0;
dayBegin.DayEndStage = 1;
dayBegin.DayReopenFlag = 0;
OperationStatus status2 = _idDB0010044Repository.AddAndSave(dayBegin);
if(status2!= null&!status2.Status)
ModelState.AddModelError(Updation failed,status2.ExceptionMessage);
else
{
CreateInwardSessionsForBranch(BranchId);
CreateOutwardSessionsForBranch(BranchId);
}

}



这是错误



会有什么问题?为什么我得到Session null。什么是解决方法

解决方案

HttpContext.Current 被设置为每个线程。所以当您使用 Parallel.ForEach 启动更多线程时,您的新线程无法访问它。解决方案是将所需的值作为参数传递,而不是依赖于您的存储库中的 HttpContext.Current








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 normal foreach loop its working fine but when i am using Parallel.ForEach it showing this error
Object reference not set to an instance of an object.

 public ActionResult Edit([DataSourceRequest] DataSourceRequest request)
        {
            try
            {
                JavaScriptSerializer js = new JavaScriptSerializer();
                List<DB0010020Vm> _listDB0010020Vm = new List<DB0010020Vm>();

                string dataDB0010020vm = Request.Form["griddetailsvm"];
                if (!string.IsNullOrEmpty(dataDB0010020vm))
                {
                    _listDB0010020Vm = js.Deserialize<List<DB0010020Vm>>(dataDB0010020vm).
                    Where(d => d.IsValid == "YES").ToList();
                }
                DateTime start = DateTime.UtcNow;


                Parallel.ForEach(_listDB0010020Vm, item =>
                {
                    doDayBegin(item.BranchId);
                });

                DateTime end = DateTime.UtcNow;
                TimeSpan duration = end - start;
                return Json(new
                {
                    success = true,
                    message = "Day Begin Process Completed Successfully!" + duration
                });
            }
            catch (Exception e)
            {
                return Json(new
                {
                    success = false,
                    message = e.Message
                });

            }
        }

  public void doDayBegin(int BranchId)
{
    var httpContext = System.Web.HttpContext.Current;
    IDB0010020Repository _idDB0010020Repository = new DB0010020Repository();
    IDB0010044Repository _idDB0010044Repository = new DB0010044Repository();

     EBS.DAL.Model.DB0010020 branchDetails = _idDB0010020Repository.FindOne(d => d.BranchId == BranchId);
    if (branchDetails == null)
    {
        ModelState.AddModelError("", "Branch not found!");
    }
    else
    {
        try
        {
            DateTime LastOpenDate = DateTime.ParseExact(Request.Form["LastOpenDate"].ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
         //   branchDetails.LastOpenDate = LastOpenDate;
    //      branchDetails.LastOpenDate = Convert.ToDateTime(Request.Form["LastOpenDate"].ToString());


        }
        catch (Exception e)
        {
          //  branchDetails.LastOpenDate = Convert.ToDateTime("2014-07-25 00:00:00.000");
        }


        OperationStatus status = _idDB0010020Repository.UpdateAndSave(branchDetails);
        if (status != null && !status.Status)
            ModelState.AddModelError("Updation failed", status.ExceptionMessage);
    }

    EBS.DAL.Model.DB0010044 dayBegin = new DB0010044();
    dayBegin.BankId = 1;
    dayBegin.BranchId = BranchId;
    dayBegin.DayBeginFlag = 1;
    //added d
    DateTime DayDate = DateTime.ParseExact(Request.Form["LastOpenDate"].ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
    dayBegin.DayDate = DayDate;
    //added d

  //  dayBegin.DayDate = Convert.ToDateTime(Request.Form["LastOpenDate"]);
    dayBegin.DayEndFlag = 0;
    dayBegin.DayEndStage = 1;
    dayBegin.DayReopenFlag = 0;
    OperationStatus status2 = _idDB0010044Repository.AddAndSave(dayBegin);
    if (status2 != null && !status2.Status)
        ModelState.AddModelError("Updation failed", status2.ExceptionMessage);
    else
    {
        CreateInwardSessionsForBranch(BranchId);
        CreateOutwardSessionsForBranch(BranchId);
    }

}


this is error

what will be the issue? why i am getting Session null. what is way to solve it

解决方案

HttpContext.Current is set per thread. So when you fire up more threads using Parallel.ForEach your new threads can't access it that way. The solution would be to pass the needed values as parameters all the way instead of relying on HttpContext.Current in your repositories.

There are several sources here on SO that covers this problem already.

The cross-thread usage of "HttpContext.Current" property and related things

HttpContext.Current.Items in different thread

Access HttpContext.Current from different threads

这篇关于Parallel.ForEach错误HttpContext.Current的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:40