How to create asynchronous web service in asp.net ?



Hi
if we are going to consume some method of web service and it is taking some time and in mean while if we have to perform some other task then we can use asynchronous web service.

Here is the simple steps to create asynchronous web service.
Step1: Create the simple web service like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/&quot;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

public WebService () {

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string HelloWorld() {
System.Threading.Thread.Sleep(1000);
return "Hello World";
}

}

Step2:Now consume the webservice and call the method in code behind page like this

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)
{
localhost.WebService ws = new localhost.WebService();
IAsyncResult myvar = ws.BeginHelloWorld(null, null);
int x = 0;
while (myvar.IsCompleted==false)
{
x += 1;

}
Label1.Text = "Result from webservice: " + ws.EndHelloWorld(myvar) + "<br> Local count while waiting:" + x.ToString();

}
}

Note: Here i have written to perform other task between being and End service method.

Advertisements

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

%d bloggers like this: