Nasıl yapılır: Zaman Uyumsuz Bir Hizmet İşlemi Uygulama

Windows Communication Foundation (WCF) uygulamalarında, bir hizmet işlemi istemciye nasıl çağrılacağı dikte edilmeden zaman uyumsuz veya zaman uyumlu olarak uygulanabilir. Örneğin, zaman uyumsuz hizmet işlemleri zaman uyumlu olarak çağrılabilir ve zaman uyumlu hizmet işlemleri zaman uyumsuz olarak çağrılabilir. İstemci uygulamasında bir işlemin zaman uyumsuz olarak nasıl çağrıldığını gösteren bir örnek için bkz . Nasıl yapılır: Hizmet İşlemlerini Zaman Uyumsuz Olarak Çağırma. Zaman uyumlu ve zaman uyumsuz işlemler hakkında daha fazla bilgi için bkz . Hizmet Sözleşmeleri Tasarlama ve Zaman Uyumsuz ve Zaman Uyumsuz İşlemler. Bu konu, zaman uyumsuz bir hizmet işleminin temel yapısını açıklar; kod tamamlanmamıştır. Hem hizmet hem de istemci tarafı için tam bir örnek için bkz . Zaman Uyumsuz.

Zaman uyumsuz bir hizmet işlemi uygulama

  1. Hizmet sözleşmenizde, .NET zaman uyumsuz tasarım yönergelerine göre zaman uyumsuz bir yöntem çifti bildirin. Begin yöntemi bir parametre, geri çağırma nesnesi ve durum nesnesi alır ve bir alıp dönüş değerini döndüren ve eşleşen End bir System.IAsyncResult yöntem döndürürSystem.IAsyncResult. Zaman uyumsuz çağrılar hakkında daha fazla bilgi için bkz . Zaman Uyumsuz Programlama Tasarım Desenleri.

  2. Begin Zaman uyumsuz yöntem çiftinin yöntemini özniteliğiyle System.ServiceModel.OperationContractAttribute işaretleyin ve özelliğini olarak trueayarlayınOperationContractAttribute.AsyncPattern. Örneğin, aşağıdaki kod 1. ve 2. adımları gerçekleştirir.

      [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. Begin/End Zaman uyumsuz tasarım yönergelerine göre hizmet sınıfınızda yöntem çiftini uygulayın. Örneğin, aşağıdaki kod örneği, zaman uyumsuz hizmet işleminin hem hem End de Begin bölümlerinde konsola bir dizenin yazıldığı ve işlemin dönüş değerinin End istemciye döndürüleceği bir uygulamayı gösterir. Kod örneğinin tamamı için Örnek bölümüne bakın.

    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
    

Örnek

Aşağıdaki kod örnekleri şunlardır:

  1. Hizmet sözleşmesi arabirimi:

    1. Zaman uyumlu SampleMethod bir işlem.

    2. Zaman uyumsuz BeginSampleMethod bir işlem.

    3. Zaman uyumsuz BeginServiceAsyncMethod/EndServiceAsyncMethod işlem çifti.

  2. Nesne kullanan bir System.IAsyncResult hizmet uygulaması.

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 synchronous 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 synchronous 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

Ayrıca bkz.