如何在C#中进行异步Web服务调用?

时间:2009-11-16 08:25:55

标签: c# web-services asynchronous

这是关于XHR和WebMethod(asmx)的纠结集群。模式很简单,我通过XHR调用Webmethod,但似乎WebMethod同步不是异步。我只需要使这种转换异步。我正在搜索和搜索(可能不是很好搜索)但找不到任何可以解决这个谜的东西。

在这里,我如何通过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;
    }
}

然后:

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

网络服务也很简单:

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

一些允许POST,GET调用的web.config条目:

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

你能指导我为异步做些什么吗?

感谢。

1 个答案:

答案 0 :(得分:0)

我打赌你会在Google上找到很多例子,但是对于后台,如果你看到有些函数列为Begin [YourWebMethodName]和End [YourWebMethodName]。在异步调用时调用Begin ...,其中我们必须传递一个异步调用完成时调用的方法,并且在此方法中除了需要调用End [YourWebMethodName]

之外的其他处理 一些代码......

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


}