ASP .Net Ajax BackgroundWorker Example Using Client Script & PageMethods

At A Glance

BackgroundWorker commonly use on Winform application. Basically it is an asynchronous process. Its thread is separate from main.
On user point of view backgroundworker works on background. Developers codes Winform async process easily with BackgroundWorker.
Here’s a Winform brief code of BackgroundWorker:

BackgroundWorker bgw = new BackgroundWorker();
bgw.WorkerReportsProgress = true;
bgw.WorkerSupportsCancellation = true;
 
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
bgw.RunWorkerAsync();

void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
          
        }

void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            
        }

void bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            
        }

However on Asp .Net Web Application there is no default BackgroundWorker server control. We have to use Asp .net Ajax to make a web async process.

Example

We have to use ScriptManager Ajax Component so that Asp .Net Web app is ajax enabled. Also we can use Client Script function PageMethods to call server methods.
EnablePageMethods attribute must be set to true on ScriptManager.

In this example, I demonstrate async process to fill up listbox with numbers of listitem.

Create a New Empty Web app and write below code on Visual Basic

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        var counter=1;
        var maxvalue;
        var canceled = false;
        function dowork() {
            if (counter == 1) {
                document.getElementById("btncancel").disabled = "";
                document.getElementById("ListBox1").options.length=0;
                maxvalue = document.getElementById("txmax").value;                
            }

            if (parseInt(counter) <= parseInt(maxvalue) && !canceled) {
                PageMethods.DoSomething(counter, DoSomething_callback);
            } else {
                RunWorkerCompleted();
            }
        }

        function DoSomething_callback(response) {

            ProgressChanged(response);
            counter++;
            setTimeout("dowork()", 0);
        }

        function ProgressChanged(response) {

            var option = document.createElement('<option value="' + response + '"></option>');
            document.getElementById("ListBox1").options.add(option);
            option.innerText = response;

        }

        function RunWorkerCompleted() {
            
            if (!canceled) {
                alert("Completed");
            } else {
                alert("Cancelled");
            }

            counter = 1;
            document.getElementById("btncancel").disabled = "disabled";
            canceled = false;
        }

        function CancelAsync() {
            canceled = true;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>
    <div>
       
        <table>
            <tr valign="top"><td><asp:ListBox ID="ListBox1" runat="server" Width="160" Height="300" Font-Size="Small">
        </asp:ListBox></td>
            <td>
            Max List Items #: <input type="text" id="txmax" size="3" value="15" /><br /><br />
            <input type="button" id="btn" value="Start" onclick="dowork()" /> &nbsp;
            <input type="button" id="btncancel" value="Stop" disabled="disabled" onclick="CancelAsync()" />
            </td>
            
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Key points are:

  1. EnablePageMethods="true" at ScriptManager attributes so we can use Page Methods
  2. Page Methods function on client script is able to call server side function. Basic example on PageMethods take a look at this link http://aspalliance.com/1922_PageMethods_In_ASPNET_AJAX.2
  3. setTimeout function to iterate dowork() execution until reach specific condition.
  4. cancelled boolean variable to indicate whether the async process is cancelled or not

At dowork() method PageMethods calls DoSomething which is server side function.

Now take a look at code behind

Imports System.Web.Services
Partial Class ProgBarClient
    Inherits System.Web.UI.Page

    <WebMethod()> _
    Public Shared Function DoSomething(ByVal counter As Integer) As String
        System.Threading.Thread.Sleep(1000)
        Return "Added Item No: " & counter.ToString()
    End Function
End Class

We imports System.Web.Services and then write <WebMethod()> and ‘Shared’ attribute to DoSomething to indicate that this function can be called from client script.
This returns a string only.

Run this web app and you will see listbox filling up after button ‘Run’ clicked and also you can cancel it at any time. This behaviour is asynchronous like BackgroundWorker do.

Cheers,
Agung Gugiaji

Advertisements

4 responses to “ASP .Net Ajax BackgroundWorker Example Using Client Script & PageMethods

  1. Pingback: BackgroundWorker Intro Part 1 – Work with ProgressBar | Enlighten Application Developer Journals

  2. Pingback: Using Asp.Net BackgroundWorker To Create Progress Bar | Enlighten Application Developer Journals

  3. Hi Agung, Any idea why I would get a JScript runtime error after clicking the “Start” button? It says “‘PageMethods’ is undefined”.

    I copied your code exactly into VS 2010.

    Thanks!

    • Hi Chuck, Thanks for visiting my blog

      Make sure you have EnablePageMethods=”true” inside ScriptManager control. So it would be
      <asp:ScriptManager ID=”ScriptManager1″ runat=”server” EnablePageMethods=”true”>

      Also look at code behind file. the related function must have <WebMethod()> attribute and ‘shared’ keyword in VB or ‘static’ in C#:
      <WebMethod()> _
      Public Shared Function DoSomething(ByVal counter As Integer) As String
      System.Threading.Thread.Sleep(1000)
      Return “Added Item No: ” & counter.ToString()
      End Function

      Hope this help

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s