Richtextbox.text引发stackerflow异常,通过事件添加行



我通过一个事件将行附加到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添加新行,但它在这一行中引发了StackOverflow异常。

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

e.数据是一个字符串。我应该怎么做才能不断添加行?

编辑

该进程链接到fluentmigrator进程,返回许多行,因为它正在对数据库运行查询。

经过一些研究和测试,我更改了代码以减少对函数的调用次数。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
    }
}}

最新更新