我正在尝试将控制台输出重定向到列表框,但是当我从另一个线程将文本写入控制台时,它会引发 InvalidOperationException
列表框编写器:
public class ListBoxWriter : TextWriter
{
private ListBox list;
private StringBuilder content = new StringBuilder();
public ListBoxWriter(ListBox list)
{
this.list = list;
}
public override void Write(char value)
{
base.Write(value);
content.Append(value);
if (value == '\n')
{
list.Items.Add(content.ToString());
content = new StringBuilder();
}
}
public override Encoding Encoding
{
get { return System.Text.Encoding.UTF8; }
}
}