本文介绍了Stringbuilder.tostring()引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我正在尝试创建一个应用程序,其中2-4个线程从不同来源获取数据
并且我必须在文本框中的表单上显示该数据.
我已经使用了一个stringbuilder,并且不断将来自不同线程的数据追加到其中.
也是一个间隔为2秒的计时器,在其滴答事件中,整个stringbuilder数据
复制到文本框.在特定长度的stringbuilder(可以说)50000之后,我将其清除.

但是有时我会遇到这种异常:

消息:索引超出范围.必须为非负数并且小于集合的大小.
参数名称:chunkLength
TargetSite:System.String ToString()

我搜索并找到了一些相对的
http://social.msdn.microsoft.com/Forums/ar/netfxbcl/thread/1051ec1c-667f-4568-a528-027cb12c34f9

但是我没有得到Textbox.Dispatcher.

现在我不确定该怎么办,也不清楚为什么会发生此异常.

代码:

Hello,

I am trying to create an application in which 2-4 threads gets data from different sources
and I have to show that data on my Form in a textbox.
I have taken a stringbuilder and i keep appending the data from different threads into it.
Also a timer with interval of 2 seconds, and on its tick event the whole stringbuilder data
is copied to the textbox. and after a particular length of stringbuilder (lets say) 50000, I clear it.

But sometimes I get this exception :

Message : Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: chunkLength
TargetSite : System.String ToString()

I have searched and found somethings relative
http://social.msdn.microsoft.com/Forums/ar/netfxbcl/thread/1051ec1c-667f-4568-a528-027cb12c34f9

But i am not getting Textbox.Dispatcher.

Now I am not sure what should I do, and also i am not clear why this exception occurs.

Code :

private void clock_Tick(object sender, EventArgs e)
 {
   try
   {
     txtMsg.Text = myClass.myStringBuilder.ToString();  //throws exception sometime
                
      if (myClass.myStringBuilder.Length == 50000)
      {
         myClass.myStringBuilder.Clear();
      }
   }
    catch (Exception ex)
    {
      //create error log
    }
 }





谢谢.





Thanks.

推荐答案

public void AddString(string s)
{
  lock(this.LockObject)
  {
     StringBuilder.Add(s);
  }
} 


object _myLockToken = new object();



您的代码将如下所示:



Your code will then be something like:

private void clock_Tick(object sender, EventArgs e)
{
  lock(_myLockToken)
  {
   try
   {
     txtMsg.Text = myClass.myStringBuilder.ToString();  //throws exception sometime
                
      if (myClass.myStringBuilder.Length == 50000)
      {
         myClass.myStringBuilder.Clear();
      }
   }
    catch (Exception ex)
    {
      //create error log
    }
  }
}



锁定声明(C#参考)

我非常有信心这会有所帮助.
(在更新GUI时,请记住BeginInvoke模式)



lock Statement (C# Reference)

I''m quite confident that this will help.
(Remember the BeginInvoke-pattern when updating the GUI)


这篇关于Stringbuilder.tostring()引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 09:49