Ler en inglés

Compartir por


IMessageSink Interfaz

Definición

Define la interfaz de un receptor de mensajes.

C#
public interface IMessageSink
C#
[System.Runtime.InteropServices.ComVisible(true)]
public interface IMessageSink
Derivado
Atributos

Ejemplos

En el ejemplo de código siguiente se muestra la implementación de la IMessageSink interfaz . Tenga en cuenta que en el ejemplo se presuponen definiciones de tipos y referencias de ensamblado que se deben proporcionar para que se compile el ejemplo.

C#
using System;
using System.Collections;
using System.Threading;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Messaging;
using Share;	

namespace MyNameSpace
{

   public class MyProxy : RealProxy
   {
      string myUrl;
      string myObjectURI;
      IMessageSink myMessageSink;

      public MyProxy(Type myType, string myUrl1)
         : base(myType)
      {

         myUrl = myUrl1;

         IChannel[] myRegisteredChannels = ChannelServices.RegisteredChannels;
         foreach (IChannel channel in myRegisteredChannels )
         {
            if (channel is IChannelSender)
            {
               IChannelSender myChannelSender = (IChannelSender)channel;

               myMessageSink = myChannelSender.CreateMessageSink(myUrl, null, out myObjectURI);
               if (myMessageSink != null)
                  break;
            }
         }

         if (myMessageSink == null)
         {
            throw new Exception("A supported channel could not be found for myUrl1:"+ myUrl);
         }
      }

      public override IMessage Invoke(IMessage myMesg)
      {
         Console.WriteLine("MyProxy.Invoke Start");

         if (myMesg is IMethodCallMessage)
            Console.WriteLine("IMethodCallMessage");

         if (myMesg is IMethodReturnMessage)
            Console.WriteLine("IMethodReturnMessage");

         Console.WriteLine("Message Properties");
         IDictionary myDictionary = myMesg.Properties;
         IDictionaryEnumerator myEnum = (IDictionaryEnumerator) myDictionary.GetEnumerator();

         while (myEnum.MoveNext())
         {
            object myKey = myEnum.Key;
            string myKeyName = myKey.ToString();
            object myValue = myEnum.Value;

            Console.WriteLine("{0} : {1}", myKeyName, myEnum.Value);
            if (myKeyName == "__Args")
            {
               object[] myArgs = (object[])myValue;
               for (int myInt = 0; myInt < myArgs.Length; myInt++)
                  Console.WriteLine("arg: {0} myValue: {1}", myInt, myArgs[myInt]);
            }

            if ((myKeyName == "__MethodSignature") && (null != myValue))
            {
               object[] myArgs = (object[])myValue;
               for (int myInt = 0; myInt < myArgs.Length; myInt++)
                  Console.WriteLine("arg: {0} myValue: {1}", myInt, myArgs[myInt]);
            }
         }

         Console.WriteLine("myUrl1 {0} object URI{1}",myUrl,myObjectURI);

         myDictionary["__Uri"] = myUrl;
         Console.WriteLine("URI {0}", myDictionary["__URI"]);
         IMessage myRetMsg = myMessageSink.SyncProcessMessage(myMesg);

         if (myRetMsg is IMethodReturnMessage)
         {
            IMethodReturnMessage myMethodReturnMessage = (IMethodReturnMessage)myRetMsg;
         }

         Console.WriteLine("MyProxy.Invoke - Finish");
         return myRetMsg;
      }
   }

   //
   // Main class that drives the whole sample
   //
   public class ProxySample
   {
      public static void Main()
      {
         ChannelServices.RegisterChannel(new HttpChannel());

         Console.WriteLine("Remoting Sample:");

         Console.WriteLine("Generate a new MyProxy using the Type");
         Type myType = typeof(MyHelloService);
         string myUrl1 = "http://localhost/myServiceAccess.soap";
         MyProxy myProxy = new MyProxy(myType, myUrl1);

         Console.WriteLine("Obtain the transparent proxy from myProxy");
         MyHelloService myService = (MyHelloService)myProxy.GetTransparentProxy();

         Console.WriteLine("Calling the Proxy");
         string myReturnString = myService.myFunction("bill");

         Console.WriteLine("Checking result : {0}", myReturnString);

         if (myReturnString == "Hi there bill, you are using .NET Remoting")
         {
            Console.WriteLine("myService.HelloMethod PASSED : returned {0}", myReturnString);
         }
         else
         {
            Console.WriteLine("myService.HelloMethod FAILED : returned {0}", myReturnString);
         }
      }
   }
}

Comentarios

Cuando se realiza una llamada de método en el proxy, la infraestructura de comunicación remota proporciona la compatibilidad necesaria para pasar los argumentos al objeto real a través de los límites de comunicación remota, llamar al método de objeto real con los argumentos y devolver los resultados al cliente del objeto proxy.

Una llamada a método remoto es un mensaje que va del extremo del cliente al extremo del servidor y, posiblemente, de nuevo. A medida que cruza los límites de comunicación remota en el camino, la llamada al método remoto pasa a través de una cadena de IMessageSink objetos. Cada receptor de la cadena recibe el objeto de mensaje, realiza una operación específica y delega al siguiente receptor de la cadena. El objeto proxy contiene una referencia a la primera IMessageSink que debe usar para iniciarse fuera de la cadena.

En el caso de las llamadas asincrónicas, en el momento de la delegación, cada receptor proporciona un receptor de respuesta (otro IMessageSink) al que llamará el siguiente receptor cuando la respuesta vuelva.

Los diferentes tipos de receptores realizan diferentes operaciones, según el tipo de objeto de mensaje recibido. Por ejemplo, un receptor podría provocar que se tome un bloqueo, otro podría aplicar la seguridad de las llamadas, otro podría realizar servicios de control de llamadas de flujo y confiabilidad, y otro podría transportar la llamada a un equipo , proceso o diferente AppDomain. Dos o más receptores de mensajes de la cadena pueden interactuar entre sí con respecto a cada acción específica.

Notas a los implementadores

Es importante tener en cuenta que el código que implementa la interfaz actual debe proporcionar implementaciones para SyncProcessMessage(IMessage) y AsyncProcessMessage(IMessage, IMessageSink), ya que las llamadas sincrónicas se pueden convertir en llamadas asincrónicas y viceversa. Ambos métodos se deben implementar, incluso si el receptor no admite el procesamiento asincrónico.

Propiedades

NextSink

Obtiene el siguiente receptor de mensajes en la cadena de receptores.

Métodos

AsyncProcessMessage(IMessage, IMessageSink)

Procesa, de forma asincrónica, el mensaje especificado.

SyncProcessMessage(IMessage)

Procesa, de forma sincrónica, el mensaje especificado.

Se aplica a

Produto Versións
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1