处理我刚刚使用 ActiveMQ 和 C# 发送的消息

发布于 2024-12-20 14:41:15 字数 1204 浏览 1 评论 0原文

我是使用 ActiveMQ 与 C# 的初学者。我创建了一个简单的窗口窗体,其中包含一个按钮和一个标签。当我单击按钮时,我会向队列发送一条消息,并且标签会使用我刚刚发送的消息进行初始化。当然,我可以直接初始化我的标签,但我希望我的表单使用队列中的消息来更新我的标签。

问题是我无法以相同的形式处理消息来更新我的标签。我的消费者代码根本没有被调用,但它是在我的表单的 Load 事件中初始化的。 这是代码

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        InitializeHandlerAMQ();
    }

    private void InitializeHandlerAMQ()
    {
        Tchat tchat = null;
        IDestination dest = _session.GetQueue(QUEUE_DESTINATION);
        using(IMessageConsumer consumer = _session.CreateConsumer(dest))
        {
            IMessage message;
            while((message = consumer.Receive(TimeSpan.FromMilliseconds(2000))) != null)
            {
                var objectMessage = message as IObjectMessage;
                if(objectMessage != null)
                {
                    tchat = objectMessage.Body as Tchat;
                    if (tchat != null)
                    {
                        textBox2.Text += string.Format("{0}{1}", tchat.Message, Environment.NewLine);
                    }
                }
            }
        }
    }

如果我关闭 Windows 窗体并重新启动它,那么我的标签已很好更新,但我不想关闭它并重新打开它。

你们有什么想法吗?

I'm a beginner at using ActiveMQ with C#. I've created a simple windows form with one button and one label. When I click on the button, i send a message to the queue and the label is initialized with the message I just sent. Of course, I could initialize my label directly but I want my form to rather consume the message from the queue in order to update my label.

The problem is I don't manage to handle the message in the same form to update my label. My consumer code is not called at all and yet, its initialized in the Load event of my form.
Here's the code

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        InitializeHandlerAMQ();
    }

    private void InitializeHandlerAMQ()
    {
        Tchat tchat = null;
        IDestination dest = _session.GetQueue(QUEUE_DESTINATION);
        using(IMessageConsumer consumer = _session.CreateConsumer(dest))
        {
            IMessage message;
            while((message = consumer.Receive(TimeSpan.FromMilliseconds(2000))) != null)
            {
                var objectMessage = message as IObjectMessage;
                if(objectMessage != null)
                {
                    tchat = objectMessage.Body as Tchat;
                    if (tchat != null)
                    {
                        textBox2.Text += string.Format("{0}{1}", tchat.Message, Environment.NewLine);
                    }
                }
            }
        }
    }

If I close my windows form and restart it, then my label is well updated but I don't want to close it and re open it.

Do you have any ideas guys ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浪漫人生路 2024-12-27 14:41:15

尝试创建一个带有这样的事件委托的类。

订阅者类别

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Apache.NMS;
using Apache.NMS.ActiveMQ;
using Apache.NMS.ActiveMQ.Commands;

namespace Utilities
{
    public delegate void QMessageReceivedDelegate(string message);
    public class MyQueueSubscriber : IDisposable
    {
        private readonly string topicName = null;
        private readonly IConnectionFactory connectionFactory;
        private readonly IConnection connection;
        private readonly ISession session;
        private readonly IMessageConsumer consumer;
        private bool isDisposed = false;
        public event QMessageReceivedDelegate OnMessageReceived;

        public MyQueueSubscriber(string queueName, string brokerUri, string clientId)
        {
            this.topicName = queueName;
            this.connectionFactory = new ConnectionFactory(brokerUri);
            this.connection = this.connectionFactory.CreateConnection();
            this.connection.ClientId = clientId;
            this.connection.Start();
            this.session = connection.CreateSession();
            ActiveMQQueue topic = new ActiveMQQueue(queueName);
            //this.consumer = this.session.CreateDurableConsumer(topic, consumerId, "2 > 1", false);
            this.consumer = this.session.CreateConsumer(topic, "2 > 1");
            this.consumer.Listener += new MessageListener(OnMessage);

        }

        public void OnMessage(IMessage message)
        {
            ITextMessage textMessage = message as ITextMessage;
            if (this.OnMessageReceived != null)
            {
                this.OnMessageReceived(textMessage.Text);
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (!this.isDisposed)
            {
                this.consumer.Dispose();
                this.session.Dispose();
                this.connection.Dispose();
                this.isDisposed = true;
            }
        }

        #endregion

    }
}

Winforms
在您的 Windows 窗体中像这样订阅队列

    MyQueueSubscriber QueueSubscriber = new MyQueueSubscriber(QueueName, ActiveMQHost, QueueClientId);
    QueueSubscriber.OnMessageReceived += new QMessageReceivedDelegate(QueueSubscriber_OnMessageReceived);

static void QueueSubscriber_OnMessageReceived(string message)
{
        SetText(message);
}

    private void SetText(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.textBox1.InvokeRequired)
        {   
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.labelname.value = text;
        }
    }

资源:
不幸的是,没有那么多资源来教授 C# 和 C#。 ActiveMQ。尝试使用 http://activemq.apache.org/nms/ 因为这非常好。

尝试查看 http://www.codersource.net/MicrosoftNet/CAdvanced/ 中的一篇小文章在CusingActiveMQ.aspx 中发布订阅。免责声明:这是我的网站,文章是我写的。抱歉,自我宣传。但我觉得这与主题相关。

Try creating a class with an event delegate like this.

A subscriber class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Apache.NMS;
using Apache.NMS.ActiveMQ;
using Apache.NMS.ActiveMQ.Commands;

namespace Utilities
{
    public delegate void QMessageReceivedDelegate(string message);
    public class MyQueueSubscriber : IDisposable
    {
        private readonly string topicName = null;
        private readonly IConnectionFactory connectionFactory;
        private readonly IConnection connection;
        private readonly ISession session;
        private readonly IMessageConsumer consumer;
        private bool isDisposed = false;
        public event QMessageReceivedDelegate OnMessageReceived;

        public MyQueueSubscriber(string queueName, string brokerUri, string clientId)
        {
            this.topicName = queueName;
            this.connectionFactory = new ConnectionFactory(brokerUri);
            this.connection = this.connectionFactory.CreateConnection();
            this.connection.ClientId = clientId;
            this.connection.Start();
            this.session = connection.CreateSession();
            ActiveMQQueue topic = new ActiveMQQueue(queueName);
            //this.consumer = this.session.CreateDurableConsumer(topic, consumerId, "2 > 1", false);
            this.consumer = this.session.CreateConsumer(topic, "2 > 1");
            this.consumer.Listener += new MessageListener(OnMessage);

        }

        public void OnMessage(IMessage message)
        {
            ITextMessage textMessage = message as ITextMessage;
            if (this.OnMessageReceived != null)
            {
                this.OnMessageReceived(textMessage.Text);
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (!this.isDisposed)
            {
                this.consumer.Dispose();
                this.session.Dispose();
                this.connection.Dispose();
                this.isDisposed = true;
            }
        }

        #endregion

    }
}

Winforms
In your windows form Subscribe to the queue like this

    MyQueueSubscriber QueueSubscriber = new MyQueueSubscriber(QueueName, ActiveMQHost, QueueClientId);
    QueueSubscriber.OnMessageReceived += new QMessageReceivedDelegate(QueueSubscriber_OnMessageReceived);

static void QueueSubscriber_OnMessageReceived(string message)
{
        SetText(message);
}

    private void SetText(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.textBox1.InvokeRequired)
        {   
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.labelname.value = text;
        }
    }

Resources:
Unfortunately there are not that many resources to teach C# & ActiveMQ. Try using http://activemq.apache.org/nms/ as this was quite good.

Try looking at a small article from http://www.codersource.net/MicrosoftNet/CAdvanced/PublishSubscribeinCusingActiveMQ.aspx. Disclaimer: This is my website and the article was written by me. Sorry for the self publicity. But I feel this is relevant to the topic.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文