开发者

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

开发者 https://www.devze.com 2023-01-13 23:52 出处:网络
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 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 r开发者_如何学JAVAesource leak when the web service is down or when there is an overload?


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.


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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号