OperationContext.GetCallbackChannel<T> Método
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Obtém um canal para a instância do cliente que chamou a operação atual.
public:
generic <typename T>
T GetCallbackChannel();
public T GetCallbackChannel<T>();
member this.GetCallbackChannel : unit -> 'T
Public Function GetCallbackChannel(Of T) () As T
Parâmetros de tipo
- T
O tipo de canal usado para chamar de volta para o cliente.
Retornos
Um canal para a instância do cliente que chamou a operação do tipo especificado na CallbackContract propriedade.
Exemplos
O exemplo de código a seguir usa a propriedade e Current o GetCallbackChannel método para criar um canal de volta para o chamador de dentro de uma operação. Todas as operações neste exemplo são operações unidirecionais, permitindo que o serviço e o cliente se comuniquem em ambas as direções de forma independente. Nesse caso, o aplicativo cliente de exemplo espera apenas uma chamada de retorno antes de sair, mas outro cliente, por exemplo, um cliente do Windows Forms, pode receber qualquer número de chamadas do serviço.
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Threading;
namespace Microsoft.WCF.Documentation
{
[ServiceContract(
Name = "SampleDuplexHello",
Namespace = "http://microsoft.wcf.documentation",
CallbackContract = typeof(IHelloCallbackContract),
SessionMode = SessionMode.Required
)]
public interface IDuplexHello
{
[OperationContract(IsOneWay = true)]
void Hello(string greeting);
}
public interface IHelloCallbackContract
{
[OperationContract(IsOneWay = true)]
void Reply(string responseToGreeting);
}
public class DuplexHello : IDuplexHello
{
public DuplexHello()
{
Console.WriteLine("Service object created: " + this.GetHashCode().ToString());
}
~DuplexHello()
{
Console.WriteLine("Service object destroyed: " + this.GetHashCode().ToString());
}
public void Hello(string greeting)
{
Console.WriteLine("Caller sent: " + greeting);
Console.WriteLine("Session ID: " + OperationContext.Current.SessionId);
Console.WriteLine("Waiting two seconds before returning call.");
// Put a slight delay to demonstrate asynchronous behavior on client.
Thread.Sleep(2000);
IHelloCallbackContract callerProxy
= OperationContext.Current.GetCallbackChannel<IHelloCallbackContract>();
string response = "Service object " + this.GetHashCode().ToString() + " received: " + greeting;
Console.WriteLine("Sending back: " + response);
callerProxy.Reply(response);
}
}
}
O cliente a seguir implementa a SampleDuplexHelloCallback mensagem de retorno de chamada para receber. O contrato de retorno de chamada importado não é o mesmo nome do serviço, devido ao uso da Name propriedade no exemplo anterior. Observe que o cliente não faz suposições sobre se ou quando pode receber um retorno de chamada; o retorno de chamada do servidor é totalmente independente da chamada de saída do cliente.
Note
Para obter um exemplo que usa a OperationContext classe em um cenário de cliente, consulte OperationContextScope.
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Threading;
namespace Microsoft.WCF.Documentation
{
public class Client : SampleDuplexHelloCallback
{
AutoResetEvent waitHandle;
public Client()
{
waitHandle = new AutoResetEvent(false);
}
public void Run()
{
// Picks up configuration from the config file.
SampleDuplexHelloClient wcfClient
= new SampleDuplexHelloClient(new InstanceContext(this));
try
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Enter a greeting to send and press ENTER: ");
Console.Write(">>> ");
Console.ForegroundColor = ConsoleColor.Green;
string greeting = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Called service with: \r\n\t" + greeting);
wcfClient.Hello(greeting);
Console.WriteLine("Execution passes service call and moves to the WaitHandle.");
this.waitHandle.WaitOne();
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("Set was called.");
Console.Write("Press ");
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("ENTER");
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write(" to exit...");
Console.ReadLine();
wcfClient.Close();
}
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();
}
}
public static void Main()
{
Client client = new Client();
client.Run();
}
public void Reply(string response)
{
Console.WriteLine("Received output.");
Console.WriteLine("\r\n\t" + response);
this.waitHandle.Set();
}
}
}
Comentários
Chame o GetCallbackChannel<T>() método para obter um canal que você pode usar para chamar operações na instância do cliente que chamou o serviço.