Calling WCF service asynchronously from ASP.NET

Posted by: Jotekes Blog, on 26 Oct 2008 | View original | Bookmarked: 0 time(s)

I was recently asked how to call WCF Service asynchronously from ASP.NET. Here's my sample code:

1) WCF Service Library Implementation

namespace WcfServiceLibrary1
{
    [ServiceContract]
    public interface ISampleService
    {
        [OperationContract]
        string SayHelloWorld();
       
    }

   
}

namespace WcfServiceLibrary1
{
  
    public class Service1 : ISampleService
    {

        #region ISampleService Members

        public string SayHelloWorld()
        {
            //Simulate it running longer than it usually takes for the page to handle request
            System.Threading.Thread.Sleep(5000);

            return "Hello World";
        }

        #endregion
    }
}

 2) ASP.NET side using the service

<%@ Page Async="true" Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Call the service" 
            onclick="Button1_Click" />
         <asp:Label ID="Label1" runat="server" ></asp:Label> 
    </div>
  
    </form>
</body>
</html>

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
         
    }

    ServiceReference1.SampleServiceClient client = null; 
    protected void Button1_Click(object sender, EventArgs e)
    {
        PageAsyncTask task = new PageAsyncTask(BeginGetAsyncData, EndGetAsyncData, null, null);
        Page.RegisterAsyncTask(task); 
    }

    IAsyncResult BeginGetAsyncData(object src, EventArgs args, AsyncCallback cb, object state)
    {
        client = new ServiceReference1.SampleServiceClient();
        return client.BeginSayHelloWorld(cb, state); 
    }

    void EndGetAsyncData(IAsyncResult ar)
    {
        string returnedValue = client.EndSayHelloWorld(ar);
        Label1.Text = DateTime.Now.ToString() + ":" + returnedValue;  
    }

}

Points to get:

- Async="True" in @page directive
- Use of PageAsyncTask to register the task (steps when starting the async action, and steps to end it) , supports tasks running parallel
- Using Begin/End methods of the WCF service (Begin/EndSayHelloWorld instead of SayHelloWorldAsync e.g not using event based implementation because ASP.NET already provides hooks to the async pattern)
- these async tasks execute between PreRender and PreRenderComplete - they're done when PreRenderComplete executes (page waits for them to execute, releasing the worker thread to the pool, and then spins up another one to end the request when async tasks are done) - e.g from user perspective it might not seem so fancy although if you can run tasks parallel, user sees it as better performance since page responds faster

Resources about async pages/ calling WCF
http://weblogs.asp.net/despos/archive/2005/10/19/427861.aspx
http://msdn.microsoft.com/en-us/library/ms734701.aspx

Share this post: email it! | bookmark it! | digg it! | reddit! | kick it! | live it!

Advertisement
Free Agile Project Management Tool from Telerik
TeamPulse Community Edition helps your team effectively capture requirements, manage project plans, assign and track work, and most importantly, be continually connected with each other.
Category: XML | Other Posts: View all posts by this blogger | Report as irrelevant | View bloggers stats | Views: 3086 | Hits: 24

Similar Posts

  • Impressions from Basta Germany Developer Conference more
  • Exporting SWF & FLV format reports in SSRS 2005 and 2008 more
  • Create a SQL Azure CRUD Application with Telerik OpenAccess and the WCF Wizard more
  • HanselMinutes Interview on RIA Services more
  • Take Two: A jQuery WCF/ASMX ServiceProxy Client more
  • Part 3: Accessing Security and Authentication in Silverlight using .NET RIA Services. more
  • Business Apps Example for Silverlight 3 RTM and .NET RIA Services July Update: Part 18: Custom Linq Provider more
  • Using the DragDropService in RadDock more
  • Remove the business context from your services more
  • CI and Configurable Service Installers more

News Categories

.NET | Agile | Ajax | Architecture | ASP.NET | BizTalk | C# | Certification | Data | DataGrid | DataSet | Debugger | DotNetNuke | Events | GridView | IIS | Indigo | JavaScript | Mobile | Mono | Patterns and Practices | Performance | Podcast | Refactor | Regex | Security | Sharepoint | Silverlight | Smart Client Applications | Software | SQL | VB.NET | Visual Studio | W3 | WCF | WinFx | WPF | WSE | XAML | XLinq | XML | XSD