Jorge
Jorge

Reputation: 155

How to asynchronously call a web service from an ASP.NET application?

I need to asychronously call a web service from an ASP.NET application. The aspx does not need the answer from the web service. It's just a simple notification.

I'm using the ...Async() method from web service stub and <%@Page Async="True" %>.

ws.HelloWorldAsync();

My problem: the web page request is waiting for the web service response.

How to solve this problem? How to avoid any resource leak when the web service is down or when there is an overload?

Upvotes: 6

Views: 2227

Answers (4)

Tim Carter
Tim Carter

Reputation: 600

A Web Service proxy normally has a Begin and End method too. You could use these. The example below shows how you can call the begin method and use a callback to complete the call. The call to MakeWebServiceAsynCall would return straight away. The using statement will make sure the object is disposed safely.

void MakeWebServiceAsynCall()
    {
        WebServiceProxy proxy = new WebServiceProxy();
        proxy.BeginHelloWorld(OnCompleted, proxy);
    }
    void OnCompleted(IAsyncResult result)
    {
        try
        {
            using (WebServiceProxy proxy = (WebServiceProxy)result.AsyncState)
                proxy.EndHelloWorld(result);
        }
        catch (Exception ex)
        {
            // handle as required
        }
    }

If you need to know whether the call was successful or not you would need to wait for the result.

Upvotes: 1

Alan Jackson
Alan Jackson

Reputation: 6511

Starting a new thread is probably the easiest solution since you don't care about getting notified of the result.

new Thread(() => ws.HelloWorld()).Start

Upvotes: 0

Chmod
Chmod

Reputation: 1014

I have used simple threads to do this before. ex:

Thread t = new Thread(delegate()
{
    ws.HelloWorld();
});
t.Start();

The thread will continue to run after the method has returned. Looking around, it seems that the ThreadPool approach isn't always recommended

Upvotes: 0

sh1ng
sh1ng

Reputation: 2973

In your scenario you may use ThreadPool ThreadPool.QueueUserWorkItem(...) to call web service in pooled thread.

Upvotes: 0

Related Questions