开发者

Asynchronous webservice in Asp.net

开发者 https://www.devze.com 2023-02-11 00:35 出处:网络
How can I set up an asynchronous web service in asp.net? I want to call a webservice to post some data to a database, but I don\'t care if the response failed or succeeded.

How can I set up an asynchronous web service in asp.net?

I want to call a webservice to post some data to a database, but I don't care if the response failed or succeeded.

I can use .net 2.0 or 3.5 only and it can be in开发者_如何学Python vb or c#.


When you create the service reference in visual studio click the "Advanced..." button and check off "Generate asynchronous operations". Then you'll have the option to make asynchronous calls against the web service.

Here's a sample of both a synchronous and the same asynchronous call to a public web service.

// http://wsf.cdyne.com/WeatherWS/Weather.asmx?wsdl
using(var wf = new WeatherForecasts.WeatherSoapClient())
{
    // example synchronous call
    wf.GetCityForecastByZIP("20850");

    // example asynchronous call
    wf.BeginGetCityForecastByZIP("20850", result => wf.EndGetCityForecastByZIP(result), null);
}

It might be tempting to just call BeginXxx and not do anything with the result since you don't care about it. You'll actually leak resources though. It's important that every BeginXxx call is matched with a corresponding EndXxx call.

Even though you have a callback that calls EndXxx, this is triggered on a thread pool thread and the original thread that called BeginXxx is free to finish as soon as the BeginXxx call is done (it doesn't wait for the response).


Webservices are usually for Request/Response style services. That said, there is a simple mechanism to do async implementation: http://msdn.microsoft.com/en-us/library/aa480516.aspx. There are ways to just do fire and forget webservices as well: http://blogs.x2line.com/al/archive/2007/05/21/3108.aspx using OneWay attribute on SoapDocumentMethod .


It doesn't sound like there is any reason that the web service has to be synchronous. Go async for maximum performance, especially if some of the tasks may be long running.

0

精彩评论

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