방법: 비동기 서비스 작업 구현
WCF(Windows Communication Foundation) 응용 프로그램에서는 클라이언트에게 호출 방법을 지시하지 않고 서비스 작업을 비동기 또는 동기적으로 구현할 수 있습니다. 예를 들어 비동기 서비스 작업을 동기적으로 호출하고, 동기 서비스 작업을 비동기적으로 호출할 수 있습니다. 클라이언트 응용 프로그램에서 작업을 비동기적으로 호출하는 방법을 보여 주는 예제는 방법: 비동기적으로 WCF 서비스 작업 호출을 참조하십시오. 동기 및 비동기 작업에 대한 자세한 내용은 서비스 계약 디자인 및 동기 및 비동기 작업을 참조하십시오. 이 항목에서는 비동기 서비스 작업의 기본 구조에 대해 설명하지만 코드가 완성되지 않았습니다. 서비스 및 클라이언트 쪽의 전체 예제는 비동기를 참조하십시오.
비동기 서비스 작업 구현
서비스 계약에서 .NET 비동기 디자인 지침에 따라 비동기 메서드 쌍을 선언합니다. Begin 메서드는 매개 변수, 콜백 개체 및 상태 개체를 가져와서 System.IAsyncResult 및 System.IAsyncResult를 가져오는 일치하는 End 메서드를 반환한 다음 반환 값을 반환합니다. 비동기 호출에 대한 자세한 내용은 Asynchronous Programming Design Patterns을 참조하십시오.
System.ServiceModel.OperationContractAttribute 특성을 가진 비동기 메서드 쌍의 Begin 메서드를 표시하고 System.ServiceModel.OperationContractAttribute.AsyncPattern 속성을 true로 설정합니다. 예를 들어 다음 코드에서는 단계 1 및 2를 수행합니다.
<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
[OperationContractAttribute(AsyncPattern=true)] IAsyncResult BeginServiceAsyncMethod(string msg, AsyncCallback callback, object asyncState); // Note: There is no OperationContractAttribute for the end method. string EndServiceAsyncMethod(IAsyncResult result); }
비동기 디자인 지침에 따라 서비스 클래스에서 Begin/End 메서드 쌍을 구현합니다. 예를 들어 다음 코드 예제에서는 비동기 서비스 작업의 Begin 및 End 부분 모두의 콘솔에 기록된 문자열의 구현 및 End 작업의 반환 값이 클라이언트에 반환되는 것을 보여 줍니다. 전체 코드 예제를 보려면 예제 단원을 참조하십시오.
예제
다음 코드 예제에서는 다음을 보여 줍니다.
다음을 포함한 서비스 계약 인터페이스:
동기
SampleMethod
작업.비동기
BeginSampleMethod
작업.비동기
BeginServiceAsyncMethod
/EndServiceAsyncMethod
작업 쌍.
System.IAsyncResult 개체를 사용하여 서비스 구현.
Imports System
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
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
}
}