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);

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.


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="">
<head runat="server">
    <script type="text/javascript">
        var counter=1;
        var maxvalue;
        var canceled = false;
        function dowork() {
            if (counter == 1) {
                document.getElementById("btncancel").disabled = "";
                maxvalue = document.getElementById("txmax").value;                

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

        function DoSomething_callback(response) {

            setTimeout("dowork()", 0);

        function ProgressChanged(response) {

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


        function RunWorkerCompleted() {
            if (!canceled) {
            } else {

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

        function CancelAsync() {
            canceled = true;
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
            <tr valign="top"><td><asp:ListBox ID="ListBox1" runat="server" Width="160" Height="300" Font-Size="Small">
            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()" />

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
  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
        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.

Agung Gugiaji

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.


    • 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
      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: Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s