Async loading with Non-blocking UI in ASP.NET with Gaia Ajax

by Jan Blomquist 18. January 2010 14:40

 

We've just published a new sample that demonstrates how to create a web page that loads items as they become available and doesn't block the UI. That means you can fully use the Web Application while another thread is spinning on the server doing the hard work.

Click here to view the sample from our nightly published samples application:
http://nightlysamples.gaiaware.net/Combinations/WebUtilities/AsyncLoading/

Or you can pickup a nightly drop here:
http://build.gaiaware.net/Trial/

The idea behind this is not new, but Gaia Ajax makes this so simple to implement and so fast thanks to the automatic diff/merge capabilities of the DRIMR technology which was introduced in Gaia Ajax 3.6. Click here to view a view about Gaia Ajax DRIMR
Sometimes Web Applications are dropped in favor of traditional Desktop applications because of performance requirements. It's not viable to create web applications that requires long time before responding. However, many functions still require lots of processsing before they can return data at all. The ideal way to solve this is the following

  1. Serve up the UI instantly.
  2. Allow the user to start the time consuming task
  3. Deliver the data for consumption in the UI as it becomes available -leaving the application operational. 

Creating the UI for this kind of application is hard enough as it requires you to dig into multi-threading and it's many pitfalls. Creating the UI as a Web Application becomes almost unthinkable as it adds yet another layer of complexity that makes the project run the risk of blowing up. That being said, any sane person reverts to the good old locally installed application with it's drawbacks to solve the problem.

Does it really have to be like that? I will argue in this blog that it's just as easy -or easier? to create a scalable, robust, multi-threaded web application in ASP.NET that doesn't block the UI -than to revert to writing desktop applications.

The reason is partially because ASP.NET is multi-threaded in itself. Each web request is tied to a Worker thread that lives throughout the duration of that page lifecycle. The process of running the lifecycle and generating the control tree is very in-expensive. In Gaia Ajax, the lifecycle running time is even chopped an additional 30%. Almost always the most expensive operation is your I/O threads. These threads often deal with files, databases, webservices and anything else which is not (in-process). I/O is so dramatically more expensive (realtive to worker threads) that Microsoft introduced the Async pattern in ASP.NET 2.0

"The problem with the ASYNC pattern is still that no WebPage is being delivered before all I/O threads are finished with their work". I argue that another option is to serve the WebPage with few or no I/O threads at all. The delivery time of the web application becomes instant.

Does that make any sense?
These I/O calls where there for a reason wheren't they? -Yes, and I am not saying that they are not going to be executed. I am simply saying that you can deliver the results over ajax by using a diff/merge strategy. In Gaia Ajax 3.6 you get automatic diff/merge for free! :-) Also the A in Ajax stands for asynchronous so they don't block the UI either.

But isn't multithreading Evil?
Yes it's evil and if you can avoid it -so you should. However, in .NET we've gotten lots of tools, code, patterns and various ways of dealing with the issue of concurrency. Modern CPU's are not scaling in terms of higher clock speed, but more cores (Link to Intel 48 cores). The LINQ to Parallells project  is now going shipped as part of .NET Framework 4.0. Instead of being afraid of the beast, I think it's time we deal with it and create the next generation of modern web applications utilizing all these cores available to us.

Ok, so how does this relate to Gaia Ajax?
Gaia makes this paradigm easy to implement with no javascript, no bloat and only the state changes are merged down to the client. Also Gaia implements an ajax request queue which only dispatches 1 ajax request at a time allowing for no concurrency issues there. You still have to deal with concurrency, race conditions, etc in your web application, but like I said that's a lot easier with all the stuff that's available to us there.

The following code snippets outline how this simple example was written. It contains 1 aspx file with a button, datagrid and timer and in the codebehind we toggle enabled and visibility properties and kick off the work which goes on in the BackgroundWorkerTask.cs file. The sample was written to be minimalistic and simple and serves more as a proof-of-concept than production ready code. The code is available in the sample too, but I'll paste it in here for your convenience.

Markup (ASPX/.aspx)

   1:   
   2:  <gaia:Button 
   3:      ID="zButton" 
   4:      runat="server" 
   5:      Text="Start Async Operation" 
   6:      OnClick="zButton_Click" />
   7:      
   8:  <gaia:Image 
   9:      ID="zImageLoader" 
  10:      ImageUrl="ajax-loader.gif" 
  11:      runat="server" 
  12:      Visible="false" />
  13:      
  14:  <gaia:GridView 
  15:      runat="server" 
  16:      ID="zGrid" 
  17:      Width="100%"
  18:      AutoGenerateColumns="false"
  19:      CssClass="async-grid">
  20:          <RowStyle CssClass="itemEven" />
  21:          <AlternatingRowStyle CssClass="itemOdd" />
  22:          <Columns>
  23:              <gaia:BoundField 
  24:                  HeaderText="Time" 
  25:                  DataField="ActivityDate" 
  26:                  DataFormatString="{0:HH:mm}" />
  27:              
  28:              <gaia:BoundField 
  29:                  HeaderText="Name" 
  30:                  ItemStyle-Width="50%"
  31:                  DataField="ActivityName" />
  32:              
  33:              <gaia:BoundField 
  34:                  HeaderText="Contact" 
  35:                  ItemStyle-Width="25%"
  36:                  DataField="ContactPerson" />
  37:          Columns>
  38:  gaia:GridView>
  39:   
  40:  <gaia:Timer 
  41:      ID="zTimer" 
  42:      runat="server" 
  43:      Milliseconds="1000"
  44:      OnTick="zTimer_Tick" 
  45:      Enabled="false" >
  46:  gaia:Timer>
  47:   
  48:   

Codebehind (C#/.cs)

   1:  namespace Gaia.WebWidgets.Samples.Combinations.WebUtilities.AsyncLoading
   2:  {
   3:      using System;
   4:      using UI;
   5:      using Utilities;
   6:      using WebWidgets.Effects;
   7:   
   8:      public partial class Default : SamplePage
   9:      {
  10:          const string CollapsedText = "Click here for more details ...";
  11:          const string ExpandedText = "Click here to hide again";
  12:   
  13:          protected void Page_Init(object sender, EventArgs e)
  14:          {
  15:              SetTimerPollingBasedOnNetworkLatency();
  16:              zViewResponse.Text = CollapsedText;
  17:          }
  18:   
  19:          protected void Page_Load(object sender, EventArgs e)
  20:          {
  21:              if (!IsPostBack) BackgroundTask = null;
  22:          }
  23:   
  24:          protected void zButton_Click(object sender, EventArgs e)
  25:          {
  26:              if (BackgroundTask.IsRunning) return;
  27:              BackgroundTask.Data.Clear(); 
  28:              BackgroundTask.RunTask();
  29:              ActivateUiTaskRunning();
  30:              DataBindGridViewToProcessedItems();
  31:          }
  32:   
  33:          protected void zTimer_Tick(object sender, EventArgs e)
  34:          {
  35:              DataBindGridViewToProcessedItems();
  36:              if (!BackgroundTask.IsRunning) DeactiveUiTaskRunning();
  37:          }
  38:   
  39:          private void DataBindGridViewToProcessedItems()
  40:          {
  41:              zGrid.DataSource = BackgroundTask.Data;
  42:              zGrid.DataBind();
  43:          }
  44:   
  45:          private void SetTimerPollingBasedOnNetworkLatency()
  46:          {
  47:              zTimer.Milliseconds = WebUtility.IsLocalhost ? 500 : 1000;
  48:          }
  49:   
  50:          private void DeactiveUiTaskRunning()
  51:          {
  52:              zImageLoader.Visible = false;
  53:              zTimer.Enabled = false;
  54:              zButton.Enabled = true;
  55:          }
  56:   
  57:          private void ActivateUiTaskRunning()
  58:          {
  59:              zTimer.Enabled = true;
  60:              zButton.Enabled = false;
  61:              zImageLoader.Visible = true;
  62:          }
  63:   
  64:          private CustomBackgroundWorker BackgroundTask
  65:          {
  66:              get
  67:              {
  68:                  return Session["worker"] as CustomBackgroundWorker ??
  69:                      (Session["worker"] = new CustomBackgroundWorker()) 
  70:                      as CustomBackgroundWorker;
  71:              }
  72:              set { Session["worker"] = value; }
  73:          }
  74:   
  75:          protected void zViewResponse_Click(object sender, EventArgs e)
  76:          {
  77:              /* some effects for show-off */
  78:   
  79:              bool show = zViewResponse.Text == CollapsedText;
  80:              zViewResponse.Text = show ? ExpandedText : CollapsedText;
  81:   
  82:              if (show)
  83:                  zCodeResponse.Effects.Add(
  84:                      new EffectParallel(
  85:                          new EffectMorph("width: 650px; height: 450px;", 0.5M),
  86:                              new EffectAppear(0.5M)));
  87:              else
  88:                  zCodeResponse.Effects.Add(
  89:                      new EffectParallel(
  90:                          new EffectMorph("width: 0px; height: 0px;", 0.5M),
  91:                              new EffectFade(0.5M)));
  92:          }
  93:      }
  94:  }

Codebehind (C#/.cs)

   1:  namespace Gaia.WebWidgets.Samples.Combinations.WebUtilities.AsyncLoading
   2:  {
   3:      using System;
   4:      using System.Collections.Generic;
   5:      using System.Threading;
   6:      using Utilities;
   7:   
   8:      public class CustomBackgroundWorker
   9:      {
  10:          private bool _isRunning;
  11:          public bool IsRunning
  12:          {
  13:              get { return _isRunning; }
  14:          }
  15:   
  16:          public void RunTask()
  17:          {
  18:              lock (this)
  19:              {
  20:                  if (_isRunning)
  21:                      throw new InvalidOperationException("The task is already running!");
  22:   
  23:                  _isRunning = true;
  24:                  new Thread(DoWork).Start();
  25:              }
  26:          }
  27:   
  28:          private ICollection _data;
  29:          public ICollection Data
  30:          {
  31:              get { return _data ?? (_data = new List()); }
  32:          }
  33:   
  34:          void DoWork()
  35:          {
  36:              try
  37:              {
  38:                  for (int i = 0; i < 15; i++)
  39:                  {
  40:                      lock (Data)
  41:                          foreach (CalendarItem item in CalendarController.CreatItems(new Random().Next(1, 3)))
  42:                              Data.Add(item);
  43:   
  44:                      Thread.Sleep(new Random().Next(300, 2000)); // Random Sleep to simulate variance
  45:                  }
  46:              }
  47:              catch  { /* Task failed (suppress exceptions in demo) */ }
  48:              finally { _isRunning = false; }
  49:          }
  50:      }
  51:  }

Though simple in nature -the async sample demonstrates a truly powerful concept which could give your web applications a boost you'd never thought possible. So give it a spin and if you like it, please drop us a message by email or use our forums : http://nightlysamples.gaiaware.net/Combinations/WebUtilities/AsyncLoading/

 

Comments

1/18/2010 4:39:37 PM #

Pingback from topsy.com

Twitter Trackbacks for
        
        Gaiaware Blog | Async loading with Non-blocking UI in ASP.NET with Gaia Ajax
        [gaiaware.net]
        on Topsy.com

topsy.com

5/20/2010 7:14:46 PM #

Pingback from 498.rkwrh.com

Rio5 Promotion Body Parts, 2009 Kia Rio5 Accessories

498.rkwrh.com

9/7/2010 6:35:30 PM #

Pingback from universityofsouthcarolina.interactiveinfonet.info

University of south carolina web site - Carolina gear - University of south carolina

universityofsouthcarolina.interactiveinfonet.info

Comments are closed