none
C# Parallel For Loop Problem - Object reference not set to an instance of an object RRS feed

  • Question

  • Hi,

     Working: 

        In my application I used For each loop on DataTable to bind data to Html template dynamically, later I'm converting this HTML template to a PDF using Spire.PDF. If DataTable has more than 100 rows (records) at the time binding data to HTML template and HTML template to PDF conversion process is very slow.


     Issue:

     Because of the above reason (slow process) I used Parallel.FOR loop instead of For loop. If I go with Parallel.For loop I am getting "object reference not set to an instance of an object" error while binding data to HTML template.





    VINOD KUMAR



    Friday, January 26, 2018 6:06 PM

All replies

  • Please provide some code. HTML template doesn't tell us anything. If this is related to using Spire.PDF though you'll need to post in their forums. We can only assist with C# specific issues.

    Michael Taylor http://www.michaeltaylorp3.net

    Friday, January 26, 2018 6:27 PM
    Moderator
  • Hello Vinod,

    object reference not set to an instance of an object

    The error means that you want to access a object whose value is null. The convert process between For loop and Parallel.FOR like below.

    For a given for loop

       for (int i = 0; i < dataTable.Rows.Count; i++) {
                    //bind data to html template      
                    //convert html template to pdf
                }

    The Parallel.FOR loop

                ParallelLoopResult result = Parallel.For(0, dataTable.Rows.Count, i =>
                {            
                    //Take each row by "dataTable.Rows[i]", Get current thread id by "Thread.CurrentThread.ManagedThreadId";         
                });
    
               Console.WriteLine(result.IsCompleted);

    Note. In Parallel.FOR content the action maybe run at different threads, you need to confirm that the code running is thread-safe or not.

    Hope above would be helpful!

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Sunday, January 28, 2018 6:29 AM
    Moderator

  •  Because of the above reason (slow process) I used Parallel.FOR loop instead of For loop. If I go with Parallel.For loop I am getting "object reference not set to an instance of an object" error while binding data to HTML template.


    Do you think this goes quicker? It is all in memory running code. Better to check why it takes time, because this kind of code with 100 rows should go in 1 seconds. 

    Success Cor

    Sunday, January 28, 2018 10:29 AM
  • Hi Vinod_.NetDev,

    Is there any update? if the issue still exist, please provide a bit more information more, such as related code, how to reproduce the issue, it will be beneficial to resolve the issue.

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, January 31, 2018 5:56 AM
    Moderator
  • Hi,

           Still I am getting same error ("object reference not set to an instance of an object" error while binding data to HTML template). I'm using below code snippet for binding data to HTML template and for converting the HTML template to PDF Files.

    Working : 

        public void BindDataToTemplate(DataTable dt_LabelInfo, string templateType, string templateName, string userName, string GUIDValue)
            {
                string templateBody = string.Empty;
                string randomNumber = string.Empty;
                int serialCount = 0;
                string filePath = string.Empty;
                string itemNo = string.Empty;
                string itemNoBarcode = string.Empty;
                string itemNoBarcodeImg = string.Empty;
                string serialValue = string.Empty;
                string serialBarCodeImg = string.Empty;

                try
                {
                    string labelTemplatesFilePath = HttpContext.Current.Server.MapPath("~/LabelTemplates/" + userName + "/");

                    for (int i = 0; i < dt_LabelInfo.Rows.Count; i++)
                    {
                        itemNo = string.Empty;
                        itemNoBarcode = string.Empty;
                        itemNoBarcodeImg = string.Empty;
                        serialValue = string.Empty;
                        serialBarCodeImg = string.Empty;

                        serialCount++;

                        if (serialCount == 10 || i == dt_LabelInfo.Rows.Count - 1)
                        {
                            templateBody += "<div style='page-break-after:avoid;'>";
                        }
                        else
                        {
                            templateBody += "<div style='page-break-after:always;'>";
                        }

                        if (!string.IsNullOrEmpty(templateType))
                        {
                            if (dt_LabelInfo.Columns.Contains("ITEM_ID"))
                            {
                                itemNo = Convert.ToString(dt_LabelInfo.Rows[i]["ITEM_ID"]) == "" ? "--" : Convert.ToString(dt_LabelInfo.Rows[i]["ITEM_ID"]);
                                if (!string.IsNullOrEmpty(itemNo) && itemNo != "--")
                                {
                                    itemNoBarcodeImg = GenerateBarCode(itemNo.Trim());
                                }
                            }
                            if (dt_LabelInfo.Columns.Contains("SERIAL_NUMBER"))
                            {
                                serialValue = Convert.ToString(dt_LabelInfo.Rows[i]["SERIAL_NUMBER"]) == "" ? "--" : Convert.ToString(dt_LabelInfo.Rows[i]["SERIAL_NUMBER"]);
                                if (!string.IsNullOrEmpty(serialValue) && serialValue != "--")
                                {
                                    serialBarCodeImg = GenerateBarCode(serialValue.Trim());
                                }
                            }                        
                        }

                        templateBody += LabelTemplate.PrepareLabelBodyWith(labelTemplatesFilePath + templateName + ".html",
                        "ItemNo", itemNo,
                        "ItemNoBarcode", "<img src='" + itemNoBarcodeImg + "'/>",
                        "SerialValue", serialValue,
                        "SerialBarcode", "<img src='" + serialBarCodeImg + "'/>"                    
                        );

                        templateBody += "</div>";
                        if (serialCount == 10 || i == dt_LabelInfo.Rows.Count - 1)
                        {
                            randomNumber = GetTenDigitRandomNumbers();
                            ConvertHTMLStringToPDF(templateBody, templateType, userName, templateType + "_" + randomNumber, GUIDValue);
                            templateBody = string.Empty;
                            serialCount = 0;
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

    Issue with Paralle.For :

      public void BindDataToTemplate(DataTable dt_LabelInfo, string templateType, string templateName, string userName, string GUIDValue)
            {
                string templateBody = string.Empty;
                string randomNumber = string.Empty;
                int serialCount = 0;
                string filePath = string.Empty;
                string itemNo = string.Empty;
                string itemNoBarcode = string.Empty;
                string itemNoBarcodeImg = string.Empty;
                string serialValue = string.Empty;
                string serialBarCodeImg = string.Empty;

                try
                {
                    string labelTemplatesFilePath = HttpContext.Current.Server.MapPath("~/LabelTemplates/" + userName + "/");


                    Parallel.For(0, dt_LabelInfo.Rows.Count, i =>
                    {
                        //for (int i = 0; i < dt_LabelInfo.Rows.Count; i++)
                        //{
                        itemNo = string.Empty;
                        itemNoBarcode = string.Empty;
                        itemNoBarcodeImg = string.Empty;
                        serialValue = string.Empty;
                        serialBarCodeImg = string.Empty;

                        serialCount++;

                        if (serialCount == 10 || i == dt_LabelInfo.Rows.Count - 1)
                        {
                            templateBody += "<div style='page-break-after:avoid;'>";
                        }
                        else
                        {
                            templateBody += "<div style='page-break-after:always;'>";
                        }

                        if (!string.IsNullOrEmpty(templateType))
                        {
                            if (dt_LabelInfo.Columns.Contains("ITEM_ID"))
                            {
                                itemNo = Convert.ToString(dt_LabelInfo.Rows[i]["ITEM_ID"]) == "" ? "--" : Convert.ToString(dt_LabelInfo.Rows[i]["ITEM_ID"]);
                                if (!string.IsNullOrEmpty(itemNo) && itemNo != "--")
                                {
                                    itemNoBarcodeImg = GenerateBarCode(itemNo.Trim());
                                }
                            }
                            if (dt_LabelInfo.Columns.Contains("SERIAL_NUMBER"))
                            {
                                serialValue = Convert.ToString(dt_LabelInfo.Rows[i]["SERIAL_NUMBER"]) == "" ? "--" : Convert.ToString(dt_LabelInfo.Rows[i]["SERIAL_NUMBER"]);
                                if (!string.IsNullOrEmpty(serialValue) && serialValue != "--")
                                {
                                    serialBarCodeImg = GenerateBarCode(serialValue.Trim());
                                }
                            }
                        }

                        templateBody += LabelTemplate.PrepareLabelBodyWith(labelTemplatesFilePath + templateName + ".html",
                        "ItemNo", itemNo,
                        "ItemNoBarcode", "<img src='" + itemNoBarcodeImg + "'/>",
                        "SerialValue", serialValue,
                        "SerialBarcode", "<img src='" + serialBarCodeImg + "'/>"
                        );

                        templateBody += "</div>";
                        if (serialCount == 10 || i == dt_LabelInfo.Rows.Count - 1)
                        {
                            randomNumber = GetTenDigitRandomNumbers();
                            ConvertHTMLStringToPDF(templateBody, templateType, userName, templateType + "_" + randomNumber, GUIDValue);
                            templateBody = string.Empty;
                            serialCount = 0;
                        }
                    });
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }



    VINOD KUMAR


    Wednesday, January 31, 2018 9:33 AM
  • Based on past experience, your null reference is likely here "string labelTemplatesFilePath = HttpContext.Current.Server.MapPath("~/LabelTemplates/" + userName + "/");"

    When you spawn new threads with Parallel.For or Parallel.ForEach, the other threads don't have access to HttpContext.Current, it will be null for them. You could try sending the value you would assign to labelTemplatesFilePath into the method as an argument.

    Wednesday, January 31, 2018 8:46 PM