HttpSimpleClientProtocol.BeginInvoke Метод

Определение

Запускает асинхронное вызов метода веб-службы XML.

protected:
 IAsyncResult ^ BeginInvoke(System::String ^ methodName, System::String ^ requestUrl, cli::array <System::Object ^> ^ parameters, AsyncCallback ^ callback, System::Object ^ asyncState);
protected IAsyncResult BeginInvoke(string methodName, string requestUrl, object[] parameters, AsyncCallback callback, object asyncState);
member this.BeginInvoke : string * string * obj[] * AsyncCallback * obj -> IAsyncResult
Protected Function BeginInvoke (methodName As String, requestUrl As String, parameters As Object(), callback As AsyncCallback, asyncState As Object) As IAsyncResult

Параметры

methodName
String

Имя метода веб-службы XML.

requestUrl
String

URL-адрес, используемый при создании WebRequest.

parameters
Object[]

Массив объектов, содержащих параметры, передаваемые методу веб-службы XML. Порядок значений в массиве соответствует порядку параметров в вызывающем методе производного класса.

callback
AsyncCallback

Делегат для вызова при завершении асинхронного вызова метода. В противном случае callbacknullделегат не вызывается.

asyncState
Object

Дополнительные сведения, предоставленные клиентом.

Возвращаемое значение

Объект IAsyncResult , который можно передать методу EndInvoke(IAsyncResult) для получения возвращаемых значений из метода веб-службы XML.

Исключения

Запрос достиг компьютера сервера, но не был успешно обработан.

Примеры

Следующий пример кода — это веб-форма ASP.NET, которая вызывает веб-службу XML с именем Math. EnterBtn_Click В функции веб-форма запускается и завершает асинхронное вызов Add метода веб-службы XML.

<%@ Page Language="VB" %>
<html>
    <script language="VB" runat="server">
    Sub EnterBtn_Click(Src As Object, E As EventArgs)
        Dim math As New MyMath.Math()
        
        ' Call to Add XML Web service method asynchronously.
        Dim result As IAsyncResult = math.BeginAdd(Convert.ToInt32(Num1.Text), Convert.ToInt32(Num2.Text), Nothing, Nothing)
        
        ' Wait for the asynchronous call to complete.
        result.AsyncWaitHandle.WaitOne()
        
        ' Complete the asynchronous call to the Add XML Web service method.
        Dim iTotal As Integer = math.EndAdd(result)
        
        Total.Text = "Total: " & iTotal.ToString()
    End Sub 'EnterBtn_Click
 
  </script>
 
    <body>
       <form action="MathClient.aspx" runat=server>
           
          Enter the two numbers you want to add and then press the Total button.
          <p>
          Number 1: <asp:textbox id="Num1" runat=server/>  +
          Number 2: <asp:textbox id="Num2" runat=server/> =
          <asp:button text="Total" Onclick="EnterBtn_Click" runat=server/>
          <p>
          <asp:label id="Total"  runat=server/>
          
       </form>
    </body>
 </html>

Следующий пример кода — это прокси-класс, созданный средством языка описания веб-служб (Wsdl.exe) для Math веб-службы XML ниже. В методе BeginAdd прокси-класса BeginInvoke метод запускает асинхронное вызов Add метода веб-службы XML.

namespace MyMath
{
   [XmlRootAttribute("snippet1>",Namespace="http://MyMath/",IsNullable=false)]
   public ref class Math: public HttpGetClientProtocol
   {
   public:
      Math()
      {
         this->Url = "http://www.contoso.com/math.asmx";
      }

      [HttpMethodAttribute(System::Web::Services::Protocols::XmlReturnReader::typeid,
      System::Web::Services::Protocols::UrlParameterWriter::typeid)]
      int Add( String^ num1, String^ num2 )
      {
         array<Object^>^temp0 = {num1,num2};
         return  *dynamic_cast<int^>(this->Invoke( "Add", String::Concat( this->Url, "/Add" ), temp0 ));
      }

      IAsyncResult^ BeginAdd( String^ num1, String^ num2, AsyncCallback^ callback, Object^ asyncState )
      {
         array<Object^>^temp1 = {num1,num2};
         return this->BeginInvoke( "Add", String::Concat( this->Url, "/Add" ), temp1, callback, asyncState );
      }

      int EndAdd( IAsyncResult^ asyncResult )
      {
         return  *dynamic_cast<int^>(this->EndInvoke( asyncResult ));
      }
   };
}
namespace MyMath
{
    [XmlRootAttribute("int", Namespace = "http://MyMath/", IsNullable = false)]
    public class Math : HttpGetClientProtocol
    {
        public Math()
        {
            this.Url = "http://www.contoso.com/math.asmx";
        }

        [HttpMethodAttribute(typeof(System.Web.Services.Protocols.XmlReturnReader),
            typeof(System.Web.Services.Protocols.UrlParameterWriter))]
        public int Add(int num1, int num2)
        {
            return ((int)(this.Invoke("Add", ((this.Url) + ("/Add")),
                new object[] { num1, num2 })));
        }

        public IAsyncResult BeginAdd(int num1, int num2, AsyncCallback callback, object asyncState)
        {
            return this.BeginInvoke("Add", ((this.Url) + ("/Add")),
                new object[] { num1, num2 }, callback, asyncState);
        }

        public int EndAdd(IAsyncResult asyncResult)
        {
            return ((int)(this.EndInvoke(asyncResult)));
        }
    }
}
Namespace MyMath
    <XmlRootAttribute("int", Namespace := "http://MyMath/", IsNullable := False)> _
    Public Class Math
        Inherits HttpGetClientProtocol
        
        Public Sub New()
            Me.Url = "http://www.contoso.com/math.asmx"
        End Sub
        
        <HttpMethodAttribute(GetType(XmlReturnReader), GetType(UrlParameterWriter))> _
        Public Function Add(num1 As String, num2 As String) As Integer
            Return CInt(Me.Invoke("Add", Me.Url + "/Add", New Object() {num1, num2}))
        End Function 'Add
        
        
        Public Function BeginAdd(num1 As String, num2 As String, callback As AsyncCallback, asyncState As Object) As IAsyncResult
            Return Me.BeginInvoke("Add", Me.Url + "/Add", New Object() {num1, num2}, callback, asyncState)
        End Function 'BeginAdd
        
        
        Public Function EndAdd(asyncResult As IAsyncResult) As Integer
            Return CInt(Me.EndInvoke(asyncResult))
        End Function 'EndAdd
    End Class
End Namespace 'MyMath

Следующий пример кода — это Math веб-служба XML, из которой был создан предыдущий прокси-класс.

<%@ WebService Language="C#" Class="Math"%>
 using System.Web.Services;
 using System;
 
 public class Math {
      [ WebMethod ]
      public int Add(int num1, int num2) {
          return num1+num2;
          }
 }
<%@ WebService Language="VB" Class="Math"%>
Imports System.Web.Services
Imports System

Public Class Math
    <WebMethod()> _
    Public Function Add(num1 As Integer, num2 As Integer) As Integer
        Return num1 + num2
    End Function 'Add
End Class 'Math

Комментарии

Параметр methodName используется для поиска типов параметров и возвращаемых значений метода, вызывающего BeginInvoke метод. Он также используется для поиска настраиваемых атрибутов, которые, возможно, были добавлены в метод. SoapDocumentMethodAttribute, SoapRpcMethodAttributeи XmlElementAttribute укажите дополнительные сведения о производном методе, который требуется для протокола HTTP.

asyncState передается callback в метод и включается в IAsyncResultBeginInvoke него. Полезно передавать сведения из контекста асинхронного вызова в обработку асинхронного результата callback.

Применяется к

См. также раздел