事件处理程序递增循环问题

Event handler incrementing loop issue

我正在使用 Xamarin.Forms 创建一个聊天机器人应用程序。每当我向机器人发送一条新消息时,都会收到回复,但会自行递增一个,即

User: Hi
Bot: Hello
User: How are you?
Bot: Good
Bot: Good

在我使用的代码中:

 public void Send()
        {
            if (!string.IsNullOrEmpty(TextToSend))
            {
                //This adds a new message to the messages collection
                Messages.Add(new ChatMessageModel() { Text = TextToSend, User = App.User });

                //This gets the chatbots response for each message
                chatbot.MainUser.ResponseReceived += async (sender, args) =>
                {
                    await Task.Delay(1500);
                    Messages.Add(new ChatMessageModel() { Text = args.Response.Text, User = App.ChatBot });
                };

                var result = chatbot.Evaluate(TextToSend);
                result.Invoke();

                //Removes the text in the Entry after message is sent
                TextToSend = string.Empty;
            }
        }

Messages.Add(new ChatMessageModel() { Text = args.Response.Text, User = App.ChatBot }); 上使用断点后,我发现它每次都会添加一条新消息,因此会自行增加。我想要一种方法来阻止这种情况并且只发生一次。

编辑:整个 Class

using BluePillApp.Models;
using BluePillApp.ViewModels.Base;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text;
using System.Windows.Input;
using Xamarin.Forms;
using Syn.Bot.Siml;
using Syn.Bot.Oscova;
using Syn.Bot.Oscova.Attributes;
using System.Reflection;
using System.IO;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace BluePillApp.ViewModels
{
    /// <summary>
    /// View model for the ChatbotPage.xaml
    /// </summary>
    public class ChatbotPageViewModel : BaseViewModel
    {
        /// <summary>
        /// A field for TextToSend
        /// </summary>
        private string _texttosend;

        /// <summary>
        /// An Instance of a new SIML Oscova Chatbot
        /// </summary>
        public OscovaBot chatbot;

        /// <summary>
        /// A collection/list of chat message items
        /// </summary>
        public ObservableCollection<ChatMessageModel> Messages { get; set; } = new ObservableCollection<ChatMessageModel>();

        /// <summary>
        /// The text that the user inputs
        /// </summary>
        public string TextToSend
        {
            get
            {
                return _texttosend;
            }

            set
            {
                if (_texttosend != value)
                {
                    _texttosend = value;

                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// A command for sending the users messages
        /// </summary>
        public ICommand SendCommand { get; set; }


        /// <summary>
        /// ChatPageViewModel Constructor
        /// </summary>
        public ChatbotPageViewModel()
        {
            SendCommand = new RelayCommand(Send);

            chatbot = new OscovaBot();
            var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MainPage)).Assembly;
            Stream stream = assembly.GetManifestResourceStream("BluePillApp.Helpers.new.siml");

            chatbot.Import(XDocument.Load(stream));
            chatbot.Trainer.StartTraining();
        }

        /// <summary>
        /// This function sends a message
        /// </summary>
        public void Send()
        {
            if (!string.IsNullOrEmpty(TextToSend))
            {
                var msgModel = new ChatMessageModel() { Text = TextToSend, User = App.User };
                //This adds a new message to the messages collection
                Messages.Add(msgModel);

                //This gets the chatbots response for each message
                chatbot.MainUser.ResponseReceived += async (sender, args) =>
                {
                    await Task.Delay(1500);
                    Messages.Add(new ChatMessageModel() { Text = args.Response.Text, User = App.ChatBot });
                };

                var result = chatbot.Evaluate(TextToSend);
                result.Invoke();

                //Removes the text in the Entry after message is sent
                TextToSend = string.Empty;
            }
        }
    }
}

你调试得很好,现在尝试保存那个该死的对象:

var msgModel = new ChatMessageModel() { Text = TextToSend, User = App.User };

//This adds a new message to the messages collection
Messages.Add(msgModel);

然后重新使用它:

//This gets the chatbots response for each message
chatbot.MainUser.ResponseReceived += async (sender, args) =>
{
    msgModel.Text = args.Response.Text;
    msgModel.User = App.ChatBot;
    await Task.Delay(1500);
    Messages.Add(msgModel);
};

我希望这能解决。

每次调用 Send 时,您都会添加一个 NEW 事件处理程序

chatbot.MainUser.ResponseReceived +=

您应该只需要分配此事件处理程序 ONCE