Event handler incrementing loop issue

﹥>﹥吖頭↗ 提交于 2020-03-02 04:20:09

问题


I'm using Xamarin.Forms to create a chatbot app. Any time I send a new message to the bot, the reply is gotten but increments itself by one i.e

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

In the code I'm using this:

 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;
            }
        }

After using a breakpoint on Messages.Add(new ChatMessageModel() { Text = args.Response.Text, User = App.ChatBot }); I found out that it adds a new message each and everytime, therefore incrementing upon itself. I would like a way to stop this and have it happen only once.

EDIT: Entire 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;
            }
        }
    }
}


回答1:


every time you call Send you are adding a NEW event handler

chatbot.MainUser.ResponseReceived +=

you should only need to assign this event handler ONCE




回答2:


You debugged very well, now try to save that damn object:

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

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

then re-use it:

//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);
};

I hope this resolves.



来源:https://stackoverflow.com/questions/60244868/event-handler-incrementing-loop-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!