Welcome to AspAdvice Sign in | Join | Help

Calling WCF service asynchronously from ASP.NET

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

Published Sunday, October 26, 2008 1:47 PM by joteke
Filed under: , , ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Calling WCF service asynchronously from ASP.NET

Ok...this shows how to call a method that takes no additonal parameters. What if the service I am trying to call takes parameters...how do I pass them in?
Tuesday, December 16, 2008 3:40 PM by Frank Prevatt

# re: Calling WCF service asynchronously from ASP.NET

Frank,

there's nothing different in that scenario. Those would be defined in the operation contract (method signature basically), and BeginSayHelloWorld method (in my sample's case) would take those parameters in, if it would have declared some.

Wednesday, December 17, 2008 1:56 PM by joteke

# re: Calling WCF service asynchronously from ASP.NET

You are rite joteke i agree with you that there is not much difference as such,as it is dependent on parameters.....cheer up. Thanx
Wednesday, February 25, 2009 12:51 AM by arnold

# re: Calling WCF service asynchronously from ASP.NET

I do not see a definition for the BeginSayHelloWorld method called in the BeginGetAsyncData... Could you please give the code for this??? Thx...
Wednesday, April 29, 2009 3:48 PM by Frank

# re: Calling WCF service asynchronously from ASP.NET

Hi, I cannot since I haven't written such. Because a proxy of a service - say generated when you add service reference in VS -  provides those methods out of the box e.g they are there for you without a line of code (every web service or WCF service proxy has corresponding Begin/End async methods per a sync method).

This is all the code I have.

Wednesday, April 29, 2009 4:16 PM by joteke

# re: Calling WCF service asynchronously from ASP.NET

Where does the variable 'client' get declared in the IAsyncResult BeginGetAsyncData(object src, EventArgs args, AsyncCallback cb, object state) method? Otherwise, it won't compile.
Tuesday, November 24, 2009 4:21 PM by randy

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below