在线程完成之前,没有获得会话值c#

时间:2014-08-19 11:26:24

标签: c# javascript multithreading

直到我的下面给出的函数执行完成,我才能得到session

的值

当ImportProcess完成后,ajax调用没有命中StatusUpdate.cs但我希望StatusUpdate.cs会在导入过程之间命中 这是我的代码请帮忙 或提供任何替代解决方案

产品Importer.cs

protected virtual ProductImportStatus ImportProduct(
            string filePath,
            bool processImage,
            bool skipImage,
            out TimeSpan timeDiff,
            string storeID
            )
        {
            TextReader reader = null;
            CsvReader csv = null;
            _status = new ProductImportStatus();
            try
            {
                LoadSkuFromCsv(filePath);

                csv = CreateCsvReader(filePath, out reader);

                // Read data line-by-line
                int i = 2;
                int invNum = 0;
                double count = 0;
                double CurrentRecordCount = 0;
                double percent = 0;
                Page page = HttpContext.Current.Handler as Page;
                ClientScriptManager cs = page.ClientScript;
                while (csv.ReadNextRecord())
                {
                    count = count + 1;
                }


                csv = CreateCsvReader(filePath, out reader);

                while (csv.ReadNextRecord())
                {
                    try
                    {
                        string vendorUsername;
                        if (!KeyUtilities.IsMultiVendorLicense())
                        {
                            vendorUsername = String.Empty;
                        }
                        else
                        {
                            vendorUsername = csv["VendorUserName"];
                        }
                        if (IsRequireFieldValid(csv["Name"]))
                        {
                            _status.AddProductNameError(i.ToString());
                        }
                        else if (IsRequireFieldValid(csv["Sku"]) ||
                            (IsSkuImported(csv["Sku"]) && !ConvertToBool(csv["UseOption"])))
                        {
                            _status.AddSKUImportedError(i.ToString());
                        }
                        else if (IsRequireFieldValid(csv["UseInventory"]) ||
                            !Int32.TryParse(csv["Stock"].ToString(), out invNum) ||
                            (ConvertToBool(csv["UseInventory"])) && IsRequireFieldValid(csv["Stock"]))
                        {
                            _status.AddInventoryAndStockError(i.ToString());
                        }
                        else if (IsRequireFieldValid(csv["CategoryID"]) || !IsCategoryExist(csv["CategoryID"]))
                        {
                            _status.AddCategoryError(i.ToString());
                        }

                        else if (IsRequireFieldValid(csv["AttributeSetId"]))
                        {
                            _status.AddAttributeSetIdError(i.ToString());
                        }
                        else if (!IsDepartmentExist(csv["DepartmentID"]))
                        {
                            _status.AddDepartmentError(i.ToString());
                        }
                        else if (!IsRelatedProductExists(csv["RelatedProducts"]))
                        {
                            _status.AddRelatedProductError(i.ToString());
                        }
                        else if (IsRequireFieldValid(csv["AttributeSetId"]) || !IsCategoryExist(csv["CategoryID"]))
                        {
                            _status.AddCategoryError(i.ToString());
                        }
                        else if (!IsVendorUserNameExist(vendorUsername))
                        {
                            _status.AddVendorUserNameError(i.ToString());
                        }
                        else if (processImage && !IsImageExists(csv))
                        {
                            _status.AddImageUploadError(i.ToString());
                        }
                        else if (!CheckOptions(csv))
                        {
                            _status.AddUseOptionError(i.ToString());
                        }
                        else if (!CheckRecurringGiftDownload(csv))
                        {
                            _status.AddRecurringGiftDownloadError(i.ToString());
                        }
                        else if (!CheckRecurringIntervalCycles(csv))
                        {
                            _status.AddRecurringIntervalCyclesError(i.ToString());
                        }
                        else if (!CheckRecurringIntervalUnit(csv))
                        {
                            _status.AddRecurringIntervalUnitError(i.ToString());
                        }
                        else if (!IsTaxClassExist(csv["IsTaxable"]))
                        {
                            _status.AddTaxClassError(i.ToString());
                        }
                        else if (!CheckMinMaxQuantity(csv))
                        {
                            _status.AddMinMaxQuantityError(i.ToString());
                        }
                        else if (!IsProductKitGroupExist(csv["IsProductKit"], csv["ProductKitGroupID"]))
                        {
                            _status.AddProductKitGroupError(i.ToString());
                        }
                        else
                        {
                            if (OverwriteProduceItem(csv, processImage, storeID, skipImage))
                            {
                                _status.AddSuccess();
                            }
                        }
                        CurrentRecordCount = CurrentRecordCount + 1;
                        percent = ((CurrentRecordCount / count) * 100);
                        String pp2 = @"{ ""CurrentStep"" : ""InPro""  ,""Percent"" : " + '"' + percent + '"' + " }";
                        HttpContext.Current.Session["Import_Progress_" + HttpContext.Current.Session.SessionID] = pp2;
                        HttpContext.Current.Session["Import_Progress"] = pp2;
                        //HttpContext.Current.Response.Write("<script type='text/javascript' language='javascript'>console.log('" + 1 + "');</script>");
                        //cs.RegisterStartupScript(page.GetType(), "WitoutUpdatePanel", "javascript:console.log('" + percent + "');", true);
                        //HttpRuntime.Cache["Import_Progress_" + HttpContext.Current.Session.SessionID] = pp2;
                        //System.Threading.Thread.Sleep(10000);


                    }
                    catch (Exception ex)
                    {
                        SaveLogFile.SaveLog(ex);
                        _status.AddOtherError(i.ToString(), ex);
                    }
                    i++;
                }
                String pp1 = @"{   ""CurrentStep"" : ""Complete""}";
                //HttpRuntime.Cache["Import_Progress_" + HttpContext.Current.Session.SessionID] = pp1;
                HttpContext.Current.Session["Import_Progress_" + HttpContext.Current.Session.SessionID] = pp1;

                try
                {
                    UpdateRelatedProductsFromIDFromSkuToID(storeID);
                }
                catch (Exception ex)
                {
                    SaveLogFile.SaveLog(ex);
                    _status.SetFatalError("Related Product - " + ex.Message);
                }

                _status.BuildSKUImportedError();
                _status.BuildProductNameError();
                _status.BuildRelatedProductError();
                if (KeyUtilities.IsMultiVendorLicense())
                {
                    _status.BuildVendorUserNameError();
                }
                _status.BuildCategoryError();
                _status.BuildDepartmentError();
                _status.BuildImageUploadError();
                _status.BuildOtherError();
                _status.BuildUseOptionError();
                _status.BuildImageProcessError();
                _status.BuildRecurringGiftDownloadError();
                _status.BuildRecurringIntervalCyclesError();
                _status.BuildRecurringIntervalUnitError();
                _status.BuildTaxClassError();
                _status.BuildMinMaxQuantityError();
                _status.BuildProductKitGroupError();
                _status.BuildInventoryAndStockError();
                _status.BuildAttributeSetIdError();
            }
            catch (Exception ex)
            {
                SaveLogFile.SaveLog(ex);
                _status.SetFatalError(ex.Message);
            }
            finally
            {
                if (csv != null)
                    csv.Dispose();

                if (reader != null)
                    reader.Dispose();
            }

            _timeEnd = DateTime.Now;
            timeDiff = _timeEnd.Subtract(_timeStart);
            return _status;
        } 

CustomeProgressbar.js

$(document).ready(function () {
        $(document).on("click", ".ImportButton", function (e) {

            UpdateStatus();
        });

    });

    var TimeOutId;
    var d;
    function UpdateStatus() {
        //setTimeout(getStatus(), 200);
       // getStatus();
        TimeOutId = window.setTimeout("getStatus()", 10);
        return true;
    }
    var uniqueId = '<%= Guid.NewGuid().ToString() %>';
        function getStatus() {
            var url = "StatusUpdate.aspx?progressstatus=" + uniqueId;
            //var url = "http://jewelthemes.com/json.asmx/test";
            $.ajax({
                url: url,
                contentType: 'application/json',
                dataType: 'json',
                cache: false,
                async: true,
                type: 'GET',
                success: function (result) {                  
                    console.log(result);
                    console.log("success");
                    d = result;
                },

                complete: function () {

                    //console.log(d)
                    if (d != null && d.CurrentStep == "Complete") {

                        window.clearTimeout(TimeOutId);
                        //TimeOutId = window.setTimeout("getStatus()", 1)
                        console.log("complete clear");
                    }
                    else {

                        TimeOutId = window.setTimeout("getStatus()", 1)
                        console.log("complete timeoutid");
                    }
                },
                error: function (result) {

                    // console.log(result);
                   TimeOutId = window.setTimeout("getStatus()", 10)
                    console.log("error");
                }
            });
            console.log("out");

        }

        function progressFn(percent) {
            debugger;
            var bars = $('.number-pb').NumberProgressBar();
            bars.reach(percent);      
        }

ProductBulkImport.cs

protected void uxImportButton_Click( object sender, EventArgs e )
    {
        uxMessagePanel.Controls.Clear();
        string localFilePath = Server.MapPath( "~/" + uxFileNameText.Text.Trim() );
        if ( !File.Exists( localFilePath ) )
        {
            Label label = new Label();
            label.ForeColor = Color.Red;
            label.Text = "File not found.";
            uxMessagePanel.Controls.Add( label );
            return;
        }

        Culture culture = DataAccessContext.CultureRepository.GetOne( uxLanguageDrop.SelectedValue );
        ProductImporter importer = new ProductImporter( culture, new FileManager() );
        ProductImportStatus status;
        TimeSpan timeDiff;
        string storeID = CurrentStoreID;
                status = importer.ImportProductOverwrite(
                    "~/" + uxFileNameText.Text.Trim(), uxImageProcessCheck.Checked, uxSkipImageProcessCheck.Checked, out timeDiff, storeID );
                UpdateMessage( status );
                UpdateTimeMessage( timeDiff, uxMessagePanel );
                break;


        AdminUtilities.ClearAllCache();
    }

StatusUpdate.cs

 protected void Page_Load(object sender, EventArgs e)
    {
        if (HttpContext.Current.Session["Import_Progress_" + HttpContext.Current.Session.SessionID] != null)
        {

            if ((Request["progressstatus"] != null) && (!string.IsNullOrEmpty(HttpContext.Current.Session["Import_Progress_" + HttpContext.Current.Session.SessionID].ToString())))
            {
                // TaskID = Request["getStatus"];
                //string st = (string)HttpRuntime.Cache["Import_Progress_" + Session.SessionID];

                string st = !string.IsNullOrEmpty(HttpContext.Current.Session["Import_Progress_" + HttpContext.Current.Session.SessionID].ToString()) ? HttpContext.Current.Session["Import_Progress_" + HttpContext.Current.Session.SessionID].ToString() : "";

                Response.Clear();
                Response.Write(st);
                Response.End();
                HttpContext.Current.Session.Remove(HttpContext.Current.Session["Import_Progress_" + HttpContext.Current.Session.SessionID].ToString());

            }
        }
    }

0 个答案:

没有答案