.NET 응용프로그램은 메시지 리스너를 사용하여 메시지를 비동기로 수신하고 예외 리스너를 사용하여 연결 문제점을 비동기로 알립니다.
메시지 리스너와 예외 리스너의 기능은 C++의 경우처럼 .NET에서도 똑같습니다. 그러나 구현에는 약간 차이가 있습니다.
메시지를 비동기로 수신하려면 다음을 수행해야 합니다.
public delegate void MessageListener(IMessage msg);
그러므로 메소드를 다음으로 정의할 수 있습니다.
void SomeMethodName(IMessage msg);
MessageListener OnMsgMethod = new MessageListener(SomeMethodName)
consumer.MessageListener = OnMsgMethod;
MessageListener를 다시 널로 설정하여 위임을 제거하십시오.
consumer.MessageListener = null;
예외 리스너는 메시지 리스너와 같은 방식으로 작동하지만 위임 정의가 다르며 메시지 처리자 이외의 연결에 지정됩니다. 이는 C++에서도 같습니다.
public delegate void ExceptionListener(Exception ex);
그러므로 메소드를 다음으로 정의할 수 있습니다.
void SomeMethodName(Exception ex);
ExceptionListener OnExMethod = new ExceptionListener(SomeMethodName)
connection.ExceptionListener = OnExMethod ;
ExceptionListener를 다시 다음으로 설정하여 위임을 제거하십시오.
null: connection.ExceptionListener = null;
예외 또는 메시지에 대한 참조가 없는 경우에는 가비지 콜렉터가 자동으로 제거할 때 예외 또는 메시지를 삭제할 필요가 없습니다.
위의 사용에 대한 샘플 코드는 다음과 같습니다.
using System; using System.Threading; using IBM.XMS; public class Sample { public static void Main() { XMSFactoryFactory factoryFactory = XMSFactoryFactory.GetInstance(XMSC.CT_RTT); IConnectionFactory connectionFactory = factoryFactory.CreateConnectionFactory(); connectionFactory.SetStringProperty(XMSC.RTT_HOST_NAME, "localhost"); connectionFactory.SetStringProperty(XMSC.RTT_PORT, "1506"); // // Create the connection and register an exception listener // IConnection connection = connectionFactory.CreateConnection(); connection.ExceptionListener = new ExceptionListener(Sample.OnException); ISession session = connection.CreateSession(false, AcknowledgeMode.AutoAcknowledge); IDestination topic = session.CreateTopic("topic://xms/sample"); // // Create the consumer and register an async message listener // IMessageConsumer consumer = session.CreateConsumer(topic); consumer.MessageListener = new MessageListener(Sample.OnMessage); connection.Start(); while (true) { Console.WriteLine("Waiting for messages...."); Thread.Sleep(1000); } } static void OnMessage(IMessage msg) { Console.WriteLine(msg); } static void OnException(Exception ex) { Console.WriteLine(ex); } }