从另一个线程将控制台输出重定向到列表框会引发InvalidOperationException

时间:2013-09-05 12:22:23

标签: c# wpf multithreading listbox

我正在尝试将控制台输出重定向到列表框,但是当我从另一个线程向控制台写入文本时,它会抛出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; }
        }
    }

1 个答案:

答案 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; }
        }
    }