Como: implementar uma operação de serviço assíncronaHow to: Implement an Asynchronous Service Operation

Em aplicativos Windows Communication Foundation (WCF), uma operação de serviço pode ser implementada de forma assíncrona ou síncrona, sem ditar ao cliente como chamá-lo.In Windows Communication Foundation (WCF) applications, a service operation can be implemented asynchronously or synchronously without dictating to the client how to call it. Por exemplo, as operações de serviço assíncronas podem ser chamadas de forma síncrona e as operações de serviço síncronas podem ser chamadas assincronamente.For example, asynchronous service operations can be called synchronously, and synchronous service operations can be called asynchronously. Para obter um exemplo que mostra como chamar uma operação de forma assíncrona em um aplicativo cliente, consulte como: chamar operações de serviço de forma assíncrona.For an example that shows how to call an operation asynchronously in a client application, see How to: Call Service Operations Asynchronously. Para obter mais informações sobre operações síncronas e assíncronas, consulte Criando contratos de serviço e operações síncronas e assíncronas.For more information about synchronous and asynchronous operations, see Designing Service Contracts and Synchronous and Asynchronous Operations. Este tópico descreve a estrutura básica de uma operação de serviço assíncrona, o código não está completo.This topic describes the basic structure of an asynchronous service operation, the code is not complete. Para obter um exemplo completo dos lados do serviço e do cliente, consulte assíncrono.For a complete example of both the service and client sides, see Asynchronous.

Implementar uma operação de serviço de forma assíncronaImplement a service operation asynchronously

  1. Em seu contrato de serviço, declare um par de métodos assíncronos de acordo com as diretrizes de design assíncrono do .NET.In your service contract, declare an asynchronous method pair according to the .NET asynchronous design guidelines. O Begin método usa um parâmetro, um objeto de retorno de chamada e um objeto de estado e retorna um System.IAsyncResult e um End método correspondente que usa um System.IAsyncResult e retorna o valor de retorno.The Begin method takes a parameter, a callback object, and a state object, and returns a System.IAsyncResult and a matching End method that takes a System.IAsyncResult and returns the return value. Para obter mais informações sobre chamadas assíncronas, consulte padrões de design de programação assíncrona.For more information about asynchronous calls, see Asynchronous Programming Design Patterns.

  2. Marque o Begin método do par de métodos assíncronos com o System.ServiceModel.OperationContractAttribute atributo e defina a OperationContractAttribute.AsyncPattern propriedade como true .Mark the Begin method of the asynchronous method pair with the System.ServiceModel.OperationContractAttribute attribute and set the OperationContractAttribute.AsyncPattern property to true. Por exemplo, o código a seguir executa as etapas 1 e 2.For example, the following code performs steps 1 and 2.

      [OperationContractAttribute(AsyncPattern=true)]
      IAsyncResult BeginServiceAsyncMethod(string msg, AsyncCallback callback, object asyncState);
    
      // Note: There is no OperationContractAttribute for the end method.
      string EndServiceAsyncMethod(IAsyncResult result);
    }
    
        <OperationContractAttribute(AsyncPattern:=True)> _
        Function BeginServiceAsyncMethod(ByVal msg As String, ByVal callback As AsyncCallback, ByVal asyncState As Object) As IAsyncResult
    
        ' Note: There is no OperationContractAttribute for the end method.
        Function EndServiceAsyncMethod(ByVal result As IAsyncResult) As String
    End Interface
    
  3. Implemente o Begin/End par de métodos em sua classe de serviço de acordo com as diretrizes de design assíncronas.Implement the Begin/End method pair in your service class according to the asynchronous design guidelines. Por exemplo, o exemplo de código a seguir mostra uma implementação na qual uma cadeia de caracteres é gravada no console tanto no Begin quanto em End partes da operação de serviço assíncrono, e o valor de retorno da End operação é retornado para o cliente.For example, the following code example shows an implementation in which a string is written to the console in both the Begin and End portions of the asynchronous service operation, and the return value of the End operation is returned to the client. Para obter o exemplo de código completo, consulte a seção de exemplo.For the complete code example, see the Example section.

    public IAsyncResult BeginServiceAsyncMethod(string msg, AsyncCallback callback, object asyncState)
    {
      Console.WriteLine("BeginServiceAsyncMethod called with: \"{0}\"", msg);
      return new CompletedAsyncResult<string>(msg);
    }
    
    public string EndServiceAsyncMethod(IAsyncResult r)
    {
      CompletedAsyncResult<string> result = r as CompletedAsyncResult<string>;
      Console.WriteLine("EndServiceAsyncMethod called with: \"{0}\"", result.Data);
      return result.Data;
    }
    
    Public Function BeginServiceAsyncMethod(ByVal msg As String, ByVal callback As AsyncCallback, ByVal asyncState As Object) As IAsyncResult Implements ISampleService.BeginServiceAsyncMethod
        Console.WriteLine("BeginServiceAsyncMethod called with: ""{0}""", msg)
        Return New CompletedAsyncResult(Of String)(msg)
    End Function
    
    Public Function EndServiceAsyncMethod(ByVal r As IAsyncResult) As String Implements ISampleService.EndServiceAsyncMethod
        Dim result As CompletedAsyncResult(Of String) = TryCast(r, CompletedAsyncResult(Of String))
        Console.WriteLine("EndServiceAsyncMethod called with: ""{0}""", result.Data)
        Return result.Data
    End Function
    

ExemploExample

Os exemplos de código a seguir mostram:The following code examples show:

  1. Uma interface de contrato de serviço com:A service contract interface with:

    1. Uma SampleMethod operação síncrona.A synchronous SampleMethod operation.

    2. Uma operação assíncrona BeginSampleMethod .An asynchronous BeginSampleMethod operation.

    3. Um par de operações assíncronas BeginServiceAsyncMethod / EndServiceAsyncMethod .An asynchronous BeginServiceAsyncMethod/EndServiceAsyncMethod operation pair.

  2. Uma implementação de serviço usando um System.IAsyncResult objeto.A service implementation using a System.IAsyncResult object.

using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Text;
using System.Threading;

namespace Microsoft.WCF.Documentation
{
  [ServiceContractAttribute(Namespace="http://microsoft.wcf.documentation")]
  public interface ISampleService{

    [OperationContractAttribute]
    string SampleMethod(string msg);

    [OperationContractAttribute(AsyncPattern = true)]
    IAsyncResult BeginSampleMethod(string msg, AsyncCallback callback, object asyncState);

    //Note: There is no OperationContractAttribute for the end method.
    string EndSampleMethod(IAsyncResult result);

    [OperationContractAttribute(AsyncPattern=true)]
    IAsyncResult BeginServiceAsyncMethod(string msg, AsyncCallback callback, object asyncState);

    // Note: There is no OperationContractAttribute for the end method.
    string EndServiceAsyncMethod(IAsyncResult result);
  }

  public class SampleService : ISampleService
  {
    #region ISampleService Members

    public string  SampleMethod(string msg)
    {
      Console.WriteLine("Called synchronous sample method with \"{0}\"", msg);
        return "The sychronous service greets you: " + msg;
    }

    // This asynchronously implemented operation is never called because
    // there is a synchronous version of the same method.
    public IAsyncResult BeginSampleMethod(string msg, AsyncCallback callback, object asyncState)
    {
      Console.WriteLine("BeginSampleMethod called with: " + msg);
      return new CompletedAsyncResult<string>(msg);
    }

    public string EndSampleMethod(IAsyncResult r)
    {
      CompletedAsyncResult<string> result = r as CompletedAsyncResult<string>;
      Console.WriteLine("EndSampleMethod called with: " + result.Data);
      return result.Data;
    }

    public IAsyncResult BeginServiceAsyncMethod(string msg, AsyncCallback callback, object asyncState)
    {
      Console.WriteLine("BeginServiceAsyncMethod called with: \"{0}\"", msg);
      return new CompletedAsyncResult<string>(msg);
    }

    public string EndServiceAsyncMethod(IAsyncResult r)
    {
      CompletedAsyncResult<string> result = r as CompletedAsyncResult<string>;
      Console.WriteLine("EndServiceAsyncMethod called with: \"{0}\"", result.Data);
      return result.Data;
    }
    #endregion
  }

  // Simple async result implementation.
  class CompletedAsyncResult<T> : IAsyncResult
  {
    T data;

    public CompletedAsyncResult(T data)
    { this.data = data; }

    public T Data
    { get { return data; } }

    #region IAsyncResult Members
    public object AsyncState
    { get { return (object)data; } }

    public WaitHandle AsyncWaitHandle
    { get { throw new Exception("The method or operation is not implemented."); } }

    public bool CompletedSynchronously
    { get { return true; } }

    public bool IsCompleted
    { get { return true; } }
    #endregion
  }
}

Imports System.Collections.Generic
Imports System.ServiceModel
Imports System.Text
Imports System.Threading

Namespace Microsoft.WCF.Documentation
    <ServiceContractAttribute(Namespace:="http://microsoft.wcf.documentation")> _
    Public Interface ISampleService

        <OperationContractAttribute> _
        Function SampleMethod(ByVal msg As String) As String

        <OperationContractAttribute(AsyncPattern:=True)> _
        Function BeginSampleMethod(ByVal msg As String, ByVal callback As AsyncCallback, ByVal asyncState As Object) As IAsyncResult

        'Note: There is no OperationContractAttribute for the end method.
        Function EndSampleMethod(ByVal result As IAsyncResult) As String

        <OperationContractAttribute(AsyncPattern:=True)> _
        Function BeginServiceAsyncMethod(ByVal msg As String, ByVal callback As AsyncCallback, ByVal asyncState As Object) As IAsyncResult

        ' Note: There is no OperationContractAttribute for the end method.
        Function EndServiceAsyncMethod(ByVal result As IAsyncResult) As String
    End Interface

    Public Class SampleService
        Implements ISampleService
#Region "ISampleService Members"

        Public Function SampleMethod(ByVal msg As String) As String Implements ISampleService.SampleMethod
            Console.WriteLine("Called synchronous sample method with ""{0}""", msg)
            Return "The sychronous service greets you: " & msg
        End Function

        ' This asynchronously implemented operation is never called because 
        ' there is a synchronous version of the same method.
        Public Function BeginSampleMethod(ByVal msg As String, ByVal callback As AsyncCallback, ByVal asyncState As Object) As IAsyncResult Implements ISampleService.BeginSampleMethod
            Console.WriteLine("BeginSampleMethod called with: " & msg)
            Return New CompletedAsyncResult(Of String)(msg)
        End Function

        Public Function EndSampleMethod(ByVal r As IAsyncResult) As String Implements ISampleService.EndSampleMethod
            Dim result As CompletedAsyncResult(Of String) = TryCast(r, CompletedAsyncResult(Of String))
            Console.WriteLine("EndSampleMethod called with: " & result.Data)
            Return result.Data
        End Function

        Public Function BeginServiceAsyncMethod(ByVal msg As String, ByVal callback As AsyncCallback, ByVal asyncState As Object) As IAsyncResult Implements ISampleService.BeginServiceAsyncMethod
            Console.WriteLine("BeginServiceAsyncMethod called with: ""{0}""", msg)
            Return New CompletedAsyncResult(Of String)(msg)
        End Function

        Public Function EndServiceAsyncMethod(ByVal r As IAsyncResult) As String Implements ISampleService.EndServiceAsyncMethod
            Dim result As CompletedAsyncResult(Of String) = TryCast(r, CompletedAsyncResult(Of String))
            Console.WriteLine("EndServiceAsyncMethod called with: ""{0}""", result.Data)
            Return result.Data
        End Function
#End Region
    End Class

    ' Simple async result implementation.
    Friend Class CompletedAsyncResult(Of T)
        Implements IAsyncResult
        Private data_Renamed As T

        Public Sub New(ByVal data As T)
            Me.data_Renamed = data
        End Sub

        Public ReadOnly Property Data() As T
            Get
                Return data_Renamed
            End Get
        End Property

#Region "IAsyncResult Members"
        Public ReadOnly Property AsyncState() As Object Implements IAsyncResult.AsyncState
            Get
                Return CObj(data_Renamed)
            End Get
        End Property

        Public ReadOnly Property AsyncWaitHandle() As WaitHandle Implements IAsyncResult.AsyncWaitHandle
            Get
                Throw New Exception("The method or operation is not implemented.")
            End Get
        End Property

        Public ReadOnly Property CompletedSynchronously() As Boolean Implements IAsyncResult.CompletedSynchronously
            Get
                Return True
            End Get
        End Property

        Public ReadOnly Property IsCompleted() As Boolean Implements IAsyncResult.IsCompleted
            Get
                Return True
            End Get
        End Property
#End Region
    End Class
End Namespace

Veja tambémSee also