开发者

How to make asynchronous webservice call in C#?

This is about a tangled cluster of XHR and WebMethod (asmx). The pattern is simple, I make calls via XHR to Webmethod, but it s开发者_如何转开发eems WebMethod are sync not async. I just need to make this transition asynchronous. I am searching and searching (might be not good in search) but couldn't find anything that can resolve this mystery.

Here, how I makes calls via XHR:

$.ajax = {
    pool: [],
    call: function(settings, onSuccess, onFailure) {
        var xhr = new XMLHttpRequest();
        xhr.open(settings.type, settings.location, settings.async);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    var result = xhr.responseXML.xml.toString();
                    onSuccess($.Encoder.htmlDecode(result));
            }
        };
        $.ajax.pool.push(xhr);
        xhr.send(null);
        return xhr;
    }
}

Then:

$.ajax.call({ type: "get", location: "Index.asmx/RaiseCallbackEvent?eventArgument=ramiz.uddin" , async: true }, function(e) {}, function(e){})

The webservice is fairly simple too:

    [WebMethod(EnableSession = true)]
    [ScriptMethod(UseHttpGet = true)]
    public string RaiseCallbackEvent(string eventArgument)
    {
      // some logic
      return "<say>hello</say>";
    }

And some web.config entries that allows POST, GET calls:

    <webServices>
      <protocols>
        <add name="HttpSoap"/>
        <add name="HttpPost"/>
        <add name="HttpGet"/>
      </protocols>
    </webServices>

Could you please guide me what I've to do for asynchronous?

Thanks.


I bet you would find a lot of examples on Google but for the background, if you see there are functions listed as Begin[YourWebMethodName] and End[YourWebMethodName]. Begin... is called when invoking asynchronously wherein we have to pass a method which is called once the async call is finished and in this method apart from other processing you need to call End[YourWebMethodName]

some code......

AsyncCallback ACB = new AsyncCallback(MyCallbackMethod);

   // Issue an asynchronous call<br>

   mywebsvc.BeginMyWebMethod1(name, ACB, mywebsvc);

   // Forget and Continue further



//This is the function known as callback function <br>
public void MyCallbackMethod(IAsyncResult asyncResult)
{
      MyWebService mywebsvc = 
  (MyWebService)asyncResult.AsyncState;

      result = webServ.EndMyWebMethod1(asyncResult);

      //use the result


}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜