Como chamar operações de serviço do WCF de maneira assíncronaHow to: Call WCF Service Operations Asynchronously

Este artigo aborda como um cliente pode acessar uma operação de serviço de forma assíncrona.This article covers how a client can access a service operation asynchronously. O serviço neste artigo implementa a ICalculator interface.The service in this article implements the ICalculator interface. O cliente pode chamar as operações nessa interface de forma assíncrona usando o modelo de chamada assíncrona controlado por evento.The client can call the operations on this interface asynchronously by using the event-driven asynchronous calling model. (Para obter mais informações sobre o modelo de chamada assíncrona baseado em evento, consulte programação multi-threaded com o padrão assíncrono baseado em evento).(For more information about the event-based asynchronous calling model, see Multithreaded Programming with the Event-based Asynchronous Pattern). Para obter um exemplo que mostra como implementar uma operação de forma assíncrona em um serviço, consulte como implementar uma operação de serviço assíncrono.For an example that shows how to implement an operation asynchronously in a service, see How to: Implement an Asynchronous Service Operation. Para obter mais informações sobre operações síncronas e assíncronas, consulte operações síncronas eassíncronas.For more information about synchronous and asynchronous operations, see Synchronous and Asynchronous Operations.

Observação

Não há suporte para o modelo de chamada assíncrona controlado por evento ao usar um ChannelFactory<TChannel> .The event-driven asynchronous calling model is not supported when using a ChannelFactory<TChannel>. Para obter informações sobre como fazer chamadas assíncronas usando o ChannelFactory<TChannel> , consulte como: chamar operações de forma assíncrona usando uma fábrica de canais.For information about making asynchronous calls using the ChannelFactory<TChannel>, see How to: Call Operations Asynchronously Using a Channel Factory.

ProcedimentoProcedure

Para chamar operações do serviço WCF de forma assíncronaTo call WCF service operations asynchronously

  1. Execute a ferramenta ferramenta de utilitário de metadados ServiceModel (Svcutil.exe) com as /async Opções de comando e e /tcv:Version35 em conjunto, conforme mostrado no comando a seguir.Run the ServiceModel Metadata Utility Tool (Svcutil.exe) tool with both the /async and the /tcv:Version35 command options together as shown in the following command.

    svcutil /n:http://Microsoft.ServiceModel.Samples,Microsoft.ServiceModel.Samples http://localhost:8000/servicemodelsamples/service/mex /a /tcv:Version35  
    

    Isso gera, além das operações assíncronas padrão síncronas e baseadas em delegados, uma classe de cliente WCF que contém:This generates, in addition to the synchronous and standard delegate-based asynchronous operations, a WCF client class that contains:

    • Duas operationName > Async operações <para uso com a abordagem de chamada assíncrona baseada em evento.Two <operationName>Async operations for use with the event-based asynchronous calling approach. Por exemplo:For example:

      public void AddAsync(double n1, double n2)
      {
          this.AddAsync(n1, n2, null);
      }
      
      public void AddAsync(double n1, double n2, object userState)
      {
          if ((this.onBeginAddDelegate == null))
          {
              this.onBeginAddDelegate = new BeginOperationDelegate(this.OnBeginAdd);
          }
          if ((this.onEndAddDelegate == null))
          {
              this.onEndAddDelegate = new EndOperationDelegate(this.OnEndAdd);
          }
          if ((this.onAddCompletedDelegate == null))
          {
              this.onAddCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnAddCompleted);
          }
          base.InvokeAsync(this.onBeginAddDelegate, new object[] {
                      n1,
                      n2}, this.onEndAddDelegate, this.onAddCompletedDelegate, userState);
      }
      
      Public Overloads Sub AddAsync(ByVal n1 As Double, ByVal n2 As Double)
          Me.AddAsync(n1, n2, Nothing)
      End Sub
      
      Public Overloads Sub AddAsync(ByVal n1 As Double, ByVal n2 As Double, ByVal userState As Object)
          If (Me.onBeginAddDelegate Is Nothing) Then
              Me.onBeginAddDelegate = AddressOf Me.OnBeginAdd
          End If
          If (Me.onEndAddDelegate Is Nothing) Then
              Me.onEndAddDelegate = AddressOf Me.OnEndAdd
          End If
          If (Me.onAddCompletedDelegate Is Nothing) Then
              Me.onAddCompletedDelegate = AddressOf Me.OnAddCompleted
          End If
          MyBase.InvokeAsync(Me.onBeginAddDelegate, New Object() {n1, n2}, Me.onEndAddDelegate, Me.onAddCompletedDelegate, userState)
      End Sub
      
    • A operação conclui eventos do formulário <operationName > Completed para uso com a abordagem de chamada assíncrona baseada em evento.Operation completed events of the form <operationName>Completed for use with the event-based asynchronous calling approach. Por exemplo:For example:

      public event System.EventHandler<AddCompletedEventArgs> AddCompleted;
      
      Public Event AddCompleted As System.EventHandler(Of AddCompletedEventArgs)
      
    • System.EventArgstipos para cada operação (do formulário <operationName > CompletedEventArgs ) para uso com a abordagem de chamada assíncrona baseada em evento.System.EventArgs types for each operation (of the form <operationName>CompletedEventArgs) for use with the event-based asynchronous calling approach. Por exemplo:For example:

      [System.Diagnostics.DebuggerStepThroughAttribute()]
      [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
      public partial class AddCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
      {
          private object[] results;
      
          public AddCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
                  base(exception, cancelled, userState)
          {       this.results = results;         }
      
          public double Result
          {
              get            {
                  base.RaiseExceptionIfNecessary();
                  return ((double)(this.results[0]));
              }
          }
      }
      
      <System.Diagnostics.DebuggerStepThroughAttribute(),  _
       System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")>  _
      Partial Public Class AddCompletedEventArgs
          Inherits System.ComponentModel.AsyncCompletedEventArgs
          
          Private results() As Object
          
          Public Sub New(ByVal results() As Object, ByVal exception As System.Exception, ByVal cancelled As Boolean, ByVal userState As Object)
              MyBase.New(exception, cancelled, userState)
              Me.results = results
          End Sub
          
          Public ReadOnly Property Result() As Double
              Get
                  MyBase.RaiseExceptionIfNecessary
                  Return CType(Me.results(0),Double)
              End Get
          End Property
      End Class
      
  2. No aplicativo de chamada, crie um método de retorno de chamada a ser chamado quando a operação assíncrona for concluída, conforme mostrado no código de exemplo a seguir.In the calling application, create a callback method to be called when the asynchronous operation is complete, as shown in the following sample code.

    // Asynchronous callbacks for displaying results.
    static void AddCallback(object sender, AddCompletedEventArgs e)
    {
        Console.WriteLine("Add Result: {0}", e.Result);
    }
    
    ' Asynchronous callbacks for displaying results.
    Private Shared Sub AddCallback(ByVal sender As Object, ByVal e As AddCompletedEventArgs)
    
        Console.WriteLine("Add Result: {0}", e.Result)
    
    End Sub
    
  3. Antes de chamar a operação, use um novo genérico System.EventHandler<TEventArgs> do tipo <operationName > EventArgs para adicionar o método de manipulador (criado na etapa anterior) ao evento <operationName > Completed .Prior to calling the operation, use a new generic System.EventHandler<TEventArgs> of type <operationName>EventArgs to add the handler method (created in the preceding step) to the <operationName>Completed event. Em seguida, chame o operationName > Async método <.Then call the <operationName>Async method. Por exemplo:For example:

    // AddAsync
    double value1 = 100.00D;
    double value2 = 15.99D;
    client.AddCompleted += new EventHandler<AddCompletedEventArgs>(AddCallback);
    client.AddAsync(value1, value2);
    Console.WriteLine("Add({0},{1})", value1, value2);
    
    ' AddAsync
    Dim value1 As Double = 100
    Dim value2 As Double = 15.99
    AddHandler client.AddCompleted, AddressOf AddCallback
    client.AddAsync(value1, value2)
    Console.WriteLine("Add({0},{1})", value1, value2)
    

ExemploExample

Observação

As diretrizes de design do modelo assíncrono baseado em eventos declaram que, se mais de um valor for retornado, um valor será retornado como a propriedade Result e os outros serão retornados como propriedades no objeto EventArgs.The design guidelines for the event-based asynchronous model state that if more than one value is returned, one value is returned as the Result property and the others are returned as properties on the EventArgs object. Um dos resultados disso é que, se um cliente importar metadados usando as opções de comando assíncrono baseadas em eventos e a operação retornar mais de um valor, o EventArgs objeto padrão retornará um valor como a Result propriedade e o restante serão propriedades do EventArgs objeto. Se você quiser receber o objeto Message como a Result propriedade e tiver os valores retornados como propriedades nesse objeto, use a opção de /messageContract comando.One result of this is that if a client imports metadata using the event-based asynchronous command options and the operation returns more than one value, the default EventArgs object returns one value as the Result property and the remainder are properties of the EventArgs object.If you want to receive the message object as the Result property and have the returned values as properties on that object, use the /messageContract command option. Isso gera uma assinatura que retorna a mensagem de resposta como a propriedade Result no objeto EventArgs.This generates a signature that returns the response message as the Result property on the EventArgs object. Todos os valores de retorno internos são propriedades do objeto da mensagem de resposta.All internal return values are then properties of the response message object.

using System;

namespace Microsoft.ServiceModel.Samples
{
    // The service contract is defined in generatedClient.cs, generated from the service by the svcutil tool.

    class Client
    {
        static void Main()
        {
            Console.WriteLine("Press <ENTER> to terminate client once the output is displayed.");
            Console.WriteLine();

            // Create a client
            CalculatorClient client = new CalculatorClient();

            // AddAsync
            double value1 = 100.00D;
            double value2 = 15.99D;
            client.AddCompleted += new EventHandler<AddCompletedEventArgs>(AddCallback);
            client.AddAsync(value1, value2);
            Console.WriteLine("Add({0},{1})", value1, value2);

            // SubtractAsync
            value1 = 145.00D;
            value2 = 76.54D;
            client.SubtractCompleted += new EventHandler<SubtractCompletedEventArgs>(SubtractCallback);
            client.SubtractAsync(value1, value2);
            Console.WriteLine("Subtract({0},{1})", value1, value2);

            // Multiply
            value1 = 9.00D;
            value2 = 81.25D;
            double result = client.Multiply(value1, value2);
            Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);

            // Divide
            value1 = 22.00D;
            value2 = 7.00D;
            result = client.Divide(value1, value2);
            Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);

            Console.ReadLine();

            //Closing the client gracefully closes the connection and cleans up resources
            client.Close();
        }

        // Asynchronous callbacks for displaying results.
        static void AddCallback(object sender, AddCompletedEventArgs e)
        {
            Console.WriteLine("Add Result: {0}", e.Result);
        }

        static void SubtractCallback(object sender, SubtractCompletedEventArgs e)
        {
            Console.WriteLine("Subtract Result: {0}", e.Result);
        }
    }
}
Namespace Microsoft.ServiceModel.Samples

    ' The service contract is defined in generatedClient.vb, generated from the service by the svcutil tool.

    Class Client

        Public Shared Sub Main()

            Console.WriteLine("Press <ENTER> to terminate client once the output is displayed.")
            Console.WriteLine()

            ' Create a client
            Dim client As New CalculatorClient()

            ' AddAsync
            Dim value1 As Double = 100
            Dim value2 As Double = 15.99
            AddHandler client.AddCompleted, AddressOf AddCallback
            client.AddAsync(value1, value2)
            Console.WriteLine("Add({0},{1})", value1, value2)

            ' SubtractAsync
            value1 = 145
            value2 = 76.54
            AddHandler client.SubtractCompleted, AddressOf SubtractCallback
            client.SubtractAsync(value1, value2)
            Console.WriteLine("Subtract({0},{1})", value1, value2)

            ' Multiply
            value1 = 9
            value2 = 81.25
            Dim result As Double = client.Multiply(value1, value2)
            Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result)

            ' Divide
            value1 = 22
            value2 = 7
            result = client.Divide(value1, value2)
            Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result)
            Console.ReadLine()

            'Closing the client gracefully closes the connection and cleans up resources
            client.Close()

        End Sub
        ' Asynchronous callbacks for displaying results.
        Private Shared Sub AddCallback(ByVal sender As Object, ByVal e As AddCompletedEventArgs)

            Console.WriteLine("Add Result: {0}", e.Result)

        End Sub
        Private Shared Sub SubtractCallback(ByVal sender As Object, ByVal e As SubtractCompletedEventArgs)

            Console.WriteLine("Subtract Result: {0}", e.Result)

        End Sub

    End Class

End Namespace

Veja tambémSee also