c# - Richtextbox.text 抛出 stackoverflow 异常,按事件添加行

c# - Richtextbox.text throws stackoverflow exception adding lines by event

我正在通过事件将行附加到 RickTextbox,我正在使用此代码。

  private void Process(object sender, DataReceivedEventArgs e)
    {
        if (richTextBox1.InvokeRequired)
        {
            BeginInvoke(new Mesage(Process), sender, e);
        }
        else
        {
            richTextBox1.Text += e.Data + Environment.NewLine;

            richTextBox1.SelectionStart = richTextBox1.Text.Length;
            richTextBox1.ScrollToCaret();

            Application.DoEvents();
        }
    }

我正在尝试向 C# WinForms 中的 RichTextbox 添加新行,但它在该行中引发了 Whosebug 异常。

 richTextBox1.Text += e.Data + Environment.NewLine;

e.Data 是一个字符串。我应该怎么做才能继续添加行?

正在编辑

The process is linked to fluentmigrator process , returning many lines because it is running queries against a database.

经过一些研究和测试,我更改了代码以减少对函数的调用次数。 Process 方法在如此短的时间内被调用了太多次,以至于引发了异常。更改后,错误不再出现。

private void Process(object sender, DataReceivedEventArgs e){
if (richTextBox1.InvokeRequired)
{
    invoked = true;
    BeginInvoke(new Mensagem(ProcessaMensagem), sender, e);
}
else
{
    try
    {       
        commands.Add(e.Data);
        count++;
        if (count % 5 == 0)
        {
            richTextBox1.Lines = commands.ToArray();
            richTextBox1.SelectionStart = richTextBox1.Text.Length;
            richTextBox1.ScrollToCaret();

            Application.DoEvents();             
        }       
    }
    catch (Exception ex)
    {
        //log logic
    }
}}