OperationContextScope OperationContextScope OperationContextScope OperationContextScope Class

정의

범위에 OperationContext 개체가 있는 블록을 만듭니다.Creates a block within which an OperationContext object is in scope.

public ref class OperationContextScope sealed : IDisposable
public sealed class OperationContextScope : IDisposable
type OperationContextScope = class
    interface IDisposable
Public NotInheritable Class OperationContextScope
Implements IDisposable
상속
OperationContextScopeOperationContextScopeOperationContextScopeOperationContextScope
구현

예제

다음 예제에서는 OperationContextScope를 사용하여 클라이언트 애플리케이션에서 새 컨텍스트를 만들어 사용자 지정 헤더를 보내는 메시지에 추가하는 방법을 보여 줍니다.The following example shows how to use the OperationContextScope to create a new context in a client application to add a custom header to the outgoing message.

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Threading;
 
public class Client : ISampleServiceCallback
{
  ManualResetEvent wait = null;

  Client()
  {
    this.wait = new ManualResetEvent(false);
  }

  public static void Main()
  {
    Client client = new Client();
    client.Run();
  }

  void Run()
  {
    // Picks up configuration from the config file.
    SampleServiceClient wcfClient = new SampleServiceClient(new InstanceContext(this));
    try
    {
      using (OperationContextScope scope = new OperationContextScope(wcfClient.InnerChannel))
      {
        MessageHeader header
          = MessageHeader.CreateHeader(
          "Service-Bound-CustomHeader",
          "http://Microsoft.WCF.Documentation",
          "Custom Happy Value."
          );
        OperationContext.Current.OutgoingMessageHeaders.Add(header);

        // Making calls.
        Console.WriteLine("Enter the greeting to send: ");
        string greeting = Console.ReadLine();

        //Console.ReadLine();
        header = MessageHeader.CreateHeader(
            "Service-Bound-OneWayHeader",
            "http://Microsoft.WCF.Documentation",
            "Different Happy Value."
          );
        OperationContext.Current.OutgoingMessageHeaders.Add(header);

        // One-way
        wcfClient.Push(greeting);
        this.wait.WaitOne();

        // Done with service. 
        wcfClient.Close();
        Console.WriteLine("Done!");
        Console.ReadLine();
      }
    }
    catch (TimeoutException timeProblem)
    {
      Console.WriteLine("The service operation timed out. " + timeProblem.Message);
      Console.ReadLine();
      wcfClient.Abort();
    }
    catch (CommunicationException commProblem)
    {
      Console.WriteLine("There was a communication problem. " + commProblem.Message);
      Console.ReadLine();
      wcfClient.Abort();
    }
  }


  #region ISampleServiceCallback Members

  public void PushBack(string msg)
  {
    Console.WriteLine("Service said: " + msg);
    this.WriteHeaders(OperationContext.Current.IncomingMessageHeaders);
    this.wait.Set();
  }

  void WriteHeaders(MessageHeaders headers)
  {
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine("IncomingHeader:");
    Console.ForegroundColor = ConsoleColor.Blue;
    foreach (MessageHeaderInfo h in headers)
    {
      if (!h.Actor.Equals(String.Empty))
        Console.WriteLine("\t" + h.Actor);
      Console.ForegroundColor = ConsoleColor.White;
      Console.WriteLine("\t" + h.Name);
      Console.ForegroundColor = ConsoleColor.Blue;
      Console.WriteLine("\t" + h.Namespace);
      Console.WriteLine("\t" + h.Relay);
      if (h.IsReferenceParameter == true)
      {
        Console.WriteLine("IsReferenceParameter header detected: " + h.ToString());
      }
    }
    Console.ResetColor();
  }
  #endregion

}
Imports System.ServiceModel
Imports System.ServiceModel.Channels
Imports System.Threading

Public Class Client
	Implements ISampleServiceCallback
  Private wait As ManualResetEvent = Nothing

  Private Sub New()
	Me.wait = New ManualResetEvent(False)
  End Sub

  Public Shared Sub Main()
	Dim client As New Client()
	client.Run()
  End Sub

  Private Sub Run()
	' Picks up configuration from the config file.
	Dim wcfClient As New SampleServiceClient(New InstanceContext(Me))
	Try
	  Using scope As New OperationContextScope(wcfClient.InnerChannel)
                Dim header As MessageHeader = MessageHeader.CreateHeader("Service-Bound-CustomHeader", _
                                    "http://Microsoft.WCF.Documentation", "Custom Happy Value.")
		OperationContext.Current.OutgoingMessageHeaders.Add(header)

		' Making calls.
		Console.WriteLine("Enter the greeting to send: ")
		Dim greeting As String = Console.ReadLine()

		'Console.ReadLine();
                header = MessageHeader.CreateHeader("Service-Bound-OneWayHeader", _
                                                    "http://Microsoft.WCF.Documentation", "Different Happy Value.")
		OperationContext.Current.OutgoingMessageHeaders.Add(header)

		' One-way
		wcfClient.Push(greeting)
		Me.wait.WaitOne()

		' Done with service. 
		wcfClient.Close()
		Console.WriteLine("Done!")
		Console.ReadLine()
	  End Using
	Catch timeProblem As TimeoutException
	  Console.WriteLine("The service operation timed out. " & timeProblem.Message)
	  Console.ReadLine()
	  wcfClient.Abort()
	Catch commProblem As CommunicationException
	  Console.WriteLine("There was a communication problem. " & commProblem.Message)
	  Console.ReadLine()
	  wcfClient.Abort()
	End Try
  End Sub


  #Region "ISampleServiceCallback Members"

  Public Sub PushBack(ByVal msg As String) Implements ISampleServiceCallback.PushBack
	Console.WriteLine("Service said: " & msg)
	Me.WriteHeaders(OperationContext.Current.IncomingMessageHeaders)
	Me.wait.Set()
  End Sub

  Private Sub WriteHeaders(ByVal headers As MessageHeaders)
	Console.ForegroundColor = ConsoleColor.Red
	Console.WriteLine("IncomingHeader:")
	Console.ForegroundColor = ConsoleColor.Blue
	For Each h As MessageHeaderInfo In headers
	  If Not h.Actor.Equals(String.Empty) Then
		Console.WriteLine(vbTab & h.Actor)
	  End If
	  Console.ForegroundColor = ConsoleColor.White
	  Console.WriteLine(vbTab & h.Name)
	  Console.ForegroundColor = ConsoleColor.Blue
	  Console.WriteLine(vbTab & h.Namespace)
	  Console.WriteLine(vbTab & h.Relay)
	  If h.IsReferenceParameter = True Then
		Console.WriteLine("IsReferenceParameter header detected: " & h.ToString())
	  End If
	Next h
	Console.ResetColor()
  End Sub
  #End Region

End Class

설명

특정 OperationContextScope 개체에 대한 범위를 만들거나, 지정된 OperationContext 개체를 사용하여 새 OperationContext 개체에 대한 범위를 만들려면 IContextChannel 클래스를 사용합니다.Use the OperationContextScope class to create a scope for a specific OperationContext object or a scope for a new OperationContext object using a specified IContextChannel object. OperationContextScope Windows Communication Foundation (WCF) 서비스 또는 WCF 클라이언트 애플리케이션에서 사용할 수 있습니다.An OperationContextScope can be used in a Windows Communication Foundation (WCF) service or WCF client application.

OperationContextScope 개체에서 현재 작업 컨텍스트를 설정하면 OperationContext를 사용하여 다음 작업을 수행할 수 있습니다.Once the OperationContextScope object has established the current operation context, you can use the OperationContext to:

  • 들어오는 메시지와 보내는 메시지의 헤더 및 기타 속성에 액세스하고 수정합니다.Access and modify incoming and outgoing message headers and other properties.

  • 디스패처, 호스트, 채널 및 확장을 포함하여 런타임에 액세스합니다.Access the runtime, including dispatchers, the host, channel, and extensions.

  • 보안, 인스턴스 및 요청 컨텍스트 등 다른 형식의 컨텍스트에 액세스합니다.Access other types of contexts, such as security, instance, and request contexts.

  • OperationContext 개체와 연결된 채널 또는 채널에서 System.ServiceModel.Channels.ISession을 구현하는 경우 연결된 채널의 세션 식별자와 연결된 채널에 액세스합니다.Access the channel associated with the OperationContext object or (if the channel implements System.ServiceModel.Channels.ISession) the associated channel's session identifier.

OperationContextScope를 만든 경우 현재 OperationContext가 저장되고 새 OperationContextCurrent 속성에 의해 반환된 컨텍스트가 됩니다.When an OperationContextScope is created, the current OperationContext is stored and the new OperationContext becomes the one returned by the Current property. OperationContextScope가 삭제된 경우 원래 OperationContext가 복원됩니다.When the OperationContextScope is disposed, the original OperationContext is restored.

경고

OperationContextScope 블록 내에서 비동기 "await" 패턴을 사용 하지 마세요.Do not use the asynchronous "await" pattern within a OperationContextScope block. 연속 작업이 발생 하면 다른 스레드에서 실행할 수 있습니다 및 OperationContextScope는 특정 스레드입니다.When the continuation occurs, it may run on a different thread and OperationContextScope is thread specific. 비동기 호출에 대 한 "await"를 호출 해야 할 경우 OperationContextScope 블록 밖에 서 사용 합니다.If you need to call "await" for an async call, use it outside of the OperationContextScope block.

생성자

OperationContextScope(IContextChannel) OperationContextScope(IContextChannel) OperationContextScope(IContextChannel) OperationContextScope(IContextChannel)

지정된 OperationContextScope을 사용하여 범위에 대해 새 IContextChannel를 만드는 OperationContext 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the OperationContextScope class that uses the specified IContextChannel to create a new OperationContext for the scope.

OperationContextScope(OperationContext) OperationContextScope(OperationContext) OperationContextScope(OperationContext) OperationContextScope(OperationContext)

지정된 OperationContextScope 개체의 범위를 만들기 위해 OperationContext 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the OperationContextScope class to create a scope for the specified OperationContext object.

메서드

Dispose() Dispose() Dispose() Dispose()

원래 OperationContext를 활성 컨텍스트로 복원하고 OperationContextScope 개체를 재활용합니다.Restores the original OperationContext to the active context and recycles the OperationContextScope object.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

지정한 개체와 현재 개체가 같은지 여부를 확인합니다.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

기본 해시 함수로 작동합니다.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

현재 인스턴스의 Type을 가져옵니다.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

현재 개체를 나타내는 문자열을 반환합니다.Returns a string that represents the current object.

(Inherited from Object)

적용 대상