我正在尝试将控制台输出重定向到列表框,但是当我从另一个线程向控制台写入文本时,它会抛出InvalidOperationException
ListBoxWriter:
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; }
}
}
答案 0 :(得分:1)
您正在从另一个线程访问UI,这意味着您必须在将项目添加到列表时使用调度程序。
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.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => list.Items.Add(content.ToString())));
content = new StringBuilder();
}
}
public override Encoding Encoding
{
get { return System.Text.Encoding.UTF8; }
}
}