WCF(Windows Communication Foundation) 애플리케이션에서 서비스 작업을 호출하는 방법을 클라이언트에 지시하지 않고 비동기적으로 또는 동기적으로 구현할 수 있습니다. 예를 들어 비동기 서비스 작업을 동기적으로 호출할 수 있으며 동기 서비스 작업을 비동기적으로 호출할 수 있습니다. 클라이언트 애플리케이션에서 비동기적으로 작업을 호출하는 방법을 보여 주는 예제는 방법: 비동기적으로서비스 작업 호출을 참조하세요. 동기 및 비동기 작업에 대한 자세한 내용은 서비스 계약 디자인 및 동기 및 비동기 작업 참조하세요. 이 항목에서는 비동기 서비스 작업의 기본 구조에 대해 설명하며 코드가 완료되지 않았습니다. 서비스 및 클라이언트 측면의 전체 예제는 비동기참조하세요.
비동기적으로 서비스 작업 구현
서비스 계약에서 .NET 비동기 디자인 지침에 따라 비동기 메서드 쌍을 선언합니다.
Begin
메서드는 매개 변수, 콜백 개체 및 상태 개체를 사용하며, System.IAsyncResult를 사용하여 반환 값을 처리하는 System.IAsyncResult 메서드와, 동일한 작업을 수행하는 일치하는End
메서드를 반환합니다. 비동기 호출에 대한 자세한 내용은 비동기 프로그래밍 디자인 패턴참조하세요.비동기 메서드 쌍의
Begin
메서드를 System.ServiceModel.OperationContractAttribute 특성으로 표시하고 OperationContractAttribute.AsyncPattern 속성을true
설정합니다. 예를 들어 다음 코드는 1단계와 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
비동기 디자인 지침에 따라 서비스 클래스에서
Begin/End
메서드 쌍을 구현합니다. 예를 들어 다음 코드 예제에서는 비동기 서비스 작업의Begin
및End
부분 모두에서 콘솔에 문자열이 기록되고End
작업의 반환 값이 클라이언트에 반환되는 구현을 보여 줍니다. 전체 코드 예제는 예제 섹션을 참조하세요.public IAsyncResult BeginServiceAsyncMethod(string msg, AsyncCallback callback, object asyncState) { Console.WriteLine($"BeginServiceAsyncMethod called with: \"{msg}\""); return new CompletedAsyncResult<string>(msg); } public string EndServiceAsyncMethod(IAsyncResult r) { CompletedAsyncResult<string> result = r as CompletedAsyncResult<string>; Console.WriteLine($"EndServiceAsyncMethod called with: \"{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
예시
다음 코드 예제는 다음을 보여 줍니다.
다음을 사용하는 서비스 계약 인터페이스:
동기식
SampleMethod
작업입니다.비동기
BeginSampleMethod
작업입니다.비동기
BeginServiceAsyncMethod
/EndServiceAsyncMethod
작업 쌍입니다.
System.IAsyncResult 개체를 사용하는 서비스 구현입니다.
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 \"{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: \"{msg}\"");
return new CompletedAsyncResult<string>(msg);
}
public string EndServiceAsyncMethod(IAsyncResult r)
{
CompletedAsyncResult<string> result = r as CompletedAsyncResult<string>;
Console.WriteLine($"EndServiceAsyncMethod called with: \"{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