0

I can't get my BackgroundWorker to update my frontend. I looked at this ex. how-do-i-run-a-simple-bit-of-code-in-a-new-thread When i run the code, it does not update my label lblSuccess.Text with 10%, 20% etc. But when it's 100% done it update the label lblSuccess.Text with Finished.

When i debug the code, it does hit the "lblSuccess.Text = string.Format("{0}% Completed", args.ProgressPercentage);" every time, so that looks like it's working fine, but the value is not being send to the frontend.

My code looks like this: AJAX:

 function GetCustomers() {
    SetHiddenGetCustomer();

    var formData = new FormData();

    var hiddenMediaName = $("#hiddenMediaName").val();
    var hiddenGetCustomers = $("#hiddenGetCustomers").val();

    formData.append("hiddenMediaName", hiddenMediaName);
    formData.append("hiddenGetCustomers", hiddenGetCustomers);

    $('#loadingmessage').show();
    $.ajax({
        type: 'post',
        url: 'ajax/Suppliers_Media_Edit.aspx',
        data: formData,
        dataType: 'html',
        contentType: false,
        processData: false,
        success: function (data) {
            $('#loadingmessage').hide();
            $('#datatable_fixed_column').html(jQuery(data).find('#datatable_fixed_column').html());
            $('#lblSuccess').html(jQuery(data).find('#lblSuccess').html());
            $('#lblError').html(jQuery(data).find('#lblError').html());

            if (jQuery(data).find('#lblSuccess').html() !== "") {
                $('#SuccessForm').show();
            } else {
                $('#ErrorForm').show();
            }
        },
        error: function (data) {
            $('#loadingmessage').hide();

            $('#lblError').html(jQuery(data).find('#lblError').html());

            $('#ErrorForm').show();
        }
    });
}

C# code:

protected void Page_Load(object sender, EventArgs e)
    {
        Boolean parsedValue;
        var hiddenSubmit = Request.Form["hiddenSubmit"];
        var hiddenLoadPage = Request.Form["hiddenLoadPage"];
        var hiddenSubmitForAllCustomers = Request.Form["hiddenSubmitForAllCustomers"];
        var hiddenGetCustomers = Request.Form["hiddenGetCustomers"];

        if (Boolean.TryParse(hiddenGetCustomers, out parsedValue))
        {
            if (parsedValue)
            {
                LoadCustomers(sender, e);
            }
        }
    }
private void LoadCustomers(object sender, EventArgs e)
        {
            var id = Request.Form["hiddenMediaName"];
            var customersToAdd = new List<Mindworking.DirectoryManagementV2.BusinessObjects.Customer>();


            BackgroundWorker bw = new BackgroundWorker();

            // this allows our worker to report progress during work
            bw.WorkerReportsProgress = true;
            bw.RunWorkerAsync();

            // what to do in the background thread
            bw.DoWork += new DoWorkEventHandler(
                delegate(object o, DoWorkEventArgs args)
                {
                    BackgroundWorker b = o as BackgroundWorker;

                    // do some simple processing for 10 seconds
                    for (int i = 1; i <= 10; i++)
                    {
                        // report the progress in percent
                        b.ReportProgress(i * 10);
                        Thread.Sleep(1000);
                    }

                });

            // what to do when progress changed (update the progress bar for example)
            bw.ProgressChanged += new ProgressChangedEventHandler(
                delegate(object o, ProgressChangedEventArgs args)
                {
                    lblSuccess.Text = string.Format("{0}% Completed", args.ProgressPercentage);
                });

            // what to do when worker completes its task (notify the user)
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
                delegate(object o, RunWorkerCompletedEventArgs args) { lblSuccess.Text = "Finished!"; });

            bw.RunWorkerAsync();
}

I hope someone can see a problem here, and tell me what i'm doing wrong.

Morten S
  • 99
  • 1
  • 8
  • Your web page works as Request > Response. You do not have communication with the client's browser until the response is sent. If you need this functionality look at websockets or less preferably, server side events. – Crowcoder Sep 04 '18 at 10:43
  • Often with background workers you will get cross thread errors. To report change you do not need to use percentage. I often use the Progress change event to send data from background worker to main thread. I create a State Class to Send data. Also why are you using Sleep() when the bacgroundworker is running Asynchronously? A form automatically implements a block and does not need a for loop. Get rid of the useless for loop. – jdweng Sep 04 '18 at 10:48
  • @jdweng I use the sleep and loop just to get some data that change, if i get it to work some other code will go in there. Do you have an example on how to use the Progress change event/State Class, i'm new to all this webforms and ajax and just want to show the user that the program is working in the back because loading all the customers takes close to 2 mins. – Morten S Sep 04 '18 at 11:00
  • The Fibonacci (second example) on following webpage does not use the for loop (first example does) : https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.backgroundworker?view=netframework-4.7.2 As long as you have a block which is in a webpage you do not need to block iin you code (just use Asynchonous methods). – jdweng Sep 04 '18 at 11:16

0 Answers0